# job-application-assistant

Adopt this skill: https://proskills.md/skills/other/lh-kevin-job-application-assistant

Page: https://proskills.md/skills/other/lh-kevin-job-application-assistant
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 10840
sha: e632bbd71a050c84e23a28b7ac0bae3cf23893f0
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/SKILL.md

```text
---
name: job-application-assistant
description: Search for companies actively hiring for a user-specified job title/role, locate their official career pages, run a background/reputation check on companies of interest (financial health, legal/labor disputes, employee reviews across 知乎/企查查/天眼查/小红书/抖音 etc.), tailor resume/cover letter materials to each opening, and assist with filling out application forms on company websites (with human confirmation before final submission). Use this whenever the user asks to find job openings, search for hiring companies, apply for jobs on company websites, do a job search + apply workflow, mass-apply to positions, check out or vet a company before applying, or mentions "投简历", "找工作", "校招/社招", "海投", "官网投递", "背调", "公司靠谱吗", "员工评价", "劳动仲裁", "帮我投递简历给招xx的公司", even if they don't use the word "skill".
---

# Job Application Assistant

Automates the *research and preparation* side of a job search — finding companies
hiring for a role and getting application materials submission-ready — while
treating the actual "submit" click as a human-in-the-loop action, since it sends
data to a third-party system on the user's behalf.

## Non-negotiable ground rules

1. **Never auto-submit without explicit per-batch confirmation.** Fill the form,
   show the user what will be sent (company, role, resume version, cover letter),
   and only submit after they say go. Confirming once for a batch of N companies
   is fine if the user explicitly asks for that — but always show the list first.
2. **Prefer the company's own official career page over third-party job boards**
   when both exist — it's usually the more precise/authoritative application
   channel and less likely to be filtered by an aggregator's ATS noise.
3. **Never try to defeat CAPTCHAs, login walls, or anti-bot checks.** Stop and
   hand control back to the user (or a browser tool that pauses for it) when one
   appears.
4. **Respect volume.** Don't fire off dozens of applications back-to-back in a
   tight loop — this looks like spam to ATS anti-abuse systems and produces
   low-quality, unreviewed submissions. Batch in small groups (5–10) with review
   checkpoints.
5. **Never fabricate experience.** Tailoring a resume means re-ordering,
   re-emphasizing, and rewording *real* content to match a JD's keywords — not
   inventing skills or titles the user doesn't have.
6. **Due-diligence findings must be sourced and balanced.** When reporting
   on a company's reputation/legal risk, attribute claims to where they came
   from, weigh official records (裁判文书网, 国家企业信用信息公示系统) above
   single social-media posts, and don't present one-off complaints as
   settled fact — see `references/company_due_diligence.md`.

## Workflow

### Step 0 — Gather inputs
Ask (or infer from context) if missing:
- Target job title/role (required) — e.g. "前端工程师", "Product Manager"
- Location / remote preference
- Any must-have filters: industry, company size, seniority, salary floor
- Whether the user has a resume file already (docx/pdf) — if not, offer to help
  draft one first; a tailored resume needs a base to tailor from.

If ambiguous, pick sensible defaults and state them rather than blocking.

### Step 1 — Find companies + openings
Run `scripts/search_target_companies.py` (requires network — see script header)
or, if network tools/connectors are available in this session (web_search,
a job-board MCP connector), search directly:
- Query aggregator sources (LinkedIn Jobs, Indeed, 智联招聘/BOSS直聘/拉勾网 as
  regionally appropriate) for `<role> <location>` to build a candidate list of
  companies + specific posting URLs.
- De-duplicate by company.

Present the candidate list to the user before going further — let them cut
companies they're not interested in.

### Step 1.5 — Company due diligence (背调)
For each company the user wants to proceed with (or upfront for the whole
shortlist, if the user prefers), pull together public signal on financial
health, legal risk, and employee sentiment before spending time tailoring
materials for it. Follow `references/company_due_diligence.md` for the
per-source query templates (工商/裁判文书, 知乎, 看准网/脉脉, 小红书, 抖音)
and how to weigh official records vs. social commentary.

Run the searches with `web_search` (or an equivalent tool in this session),
compile the findings into the JSON shape documented in
`scripts/due_diligence_report.py`, then run it to produce a report — write
it into the **same output folder** you'll later put the applications
dashboard in, so the relative link between them works:

    python scripts/due_diligence_report.py --input <company>_findings.json \
        --out <company>_report.html --format html

Then attach a short risk summary to the tracker so it surfaces in the main
dashboard instead of sitting in a disconnected file:

    python scripts/track_applications.py diligence \
        --company "<company>" --role "<role>" \
        --risk low|medium|high --report <company>_report.html \
        --summary "<one-line summary>"

`diligence` creates a minimal tracker record if one doesn't exist yet —
useful for vetting a company before deciding whether to even apply. The
dashboard (`track_applications.py dashboard`) then shows a 背调 risk badge
per row with a link straight to the full report, plus a "高风险公司" count
in the summary cards — so the two views (all applications, and how risky
each company looked) live side by side without merging into one bloated
file.

Surface any red flags (劳动仲裁记录, 失信被执行人, repeated/corroborated
complaints about unpaid wages or excessive overtime) prominently and let the
user decide whether to still apply — don't silently filter companies out,
and don't state unverified social-media claims as settled fact.

### Step 2 — Find each company's official career page
For each approved company, run `scripts/find_career_page.py <company_name>`
to locate `careers.<company>.com` / `<company>.com/careers` / `/jobs` style
pages, distinguishing it from the aggregator listing found in Step 1.
Fall back to the aggregator listing only if no official page is found.

### Step 3 — Tailor materials per company
Before starting a new company, run
`scripts/track_applications.py check --company "<name>"` — if there's
already a record, show the user its status instead of duplicating work
(mirrors how established auto-apply tools skip already-applied companies).

For each opening:
- Read the JD (fetch the posting page).
- If the docx skill is available and the user wants a Word resume, use it to
  produce a tailored version (see `/mnt/skills/public/docx/SKILL.md`) —
  reorder bullet points and adjust the summary to mirror the JD's key
  requirements/keywords, using only the user's real experience.
- Keep a base resume version untouched; tailored copies go in per-company
  files so the user can compare.

### Step 4 — Fill the application form
- Identify the ATS platform behind the career page using
  `references/ats_platforms.md` (Greenhouse/Lever/Workday/SmartRecruiters/
  iCIMS/自建系统 all have recognizable URL or DOM fingerprints).
- If a browser automation tool is available in this session (e.g. a connected
  browsing MCP), use it to open the form and fill the known fields (name,
  email, phone, resume upload, cover letter, standard EEO/optional questions)
  using `scripts/ats_form_filler.py` as a reference for field-mapping per ATS.
- If running `scripts/ats_form_filler.py` directly, always let it run with a
  **visible** browser (its default) — never pass `--headless` unless you're
  sure the form has no bot-check. Headless hides any CAPTCHA from the user
  entirely, which just looks like the script hanging. The script detects
  common CAPTCHA/challenge markers and pauses at the terminal for the user
  to solve it by hand in the visible window; it never tries to bypass one.
- If no browser tool is available, fill and describe the form fields inline
  and hand the user a checklist + direct link to finish manually.
- **Stop before clicking submit.** Show the filled summary and wait for
  explicit "submit" / "投递" confirmation from the user. Only then re-run
  with `--confirm-submit`.

### Step 5 — Track results
After each confirmed submission (or manual completion), log it with
`scripts/track_applications.py add` — company, role, date, channel (official
site / aggregator), ATS, status, link, notes. This becomes the running
record the user can query later:
- `list [--status ...]` — filtered raw list
- `stats` — totals by status/channel, this-week count
- `followups --days N` — submitted applications stale for N+ days, good
  candidates for a polite check-in message
- `dashboard --out dashboard.html` — self-contained HTML dashboard (summary
  cards + status breakdown + full table, with a 背调 risk badge/link per row
  if due-diligence info was attached in Step 1.5) the user can open in a
  browser; use this whenever they ask to "整理/查看/汇总投递数据" or want an
  overview rather than a raw list
- `export --out applications.csv` — for opening in Excel/Google Sheets

See `references/similar_projects.md` for the prior art these tracker
features and the confirm-before-submit / CAPTCHA-handling design were
checked against.

## Reference files
- `references/ats_platforms.md` — how to recognize each major ATS and what
  fields it typically exposes, for building selector-based automation.
- `scripts/search_target_companies.py` — network search helper (needs an
  environment with internet access; will no-op with a clear error otherwise).
- `scripts/find_career_page.py` — heuristics for finding the *official*
  careers page vs. an aggregator mirror.
- `scripts/ats_form_filler.py` — Playwright-based template for filling common
  ATS forms; requires `playwright` installed and a real browser context, and
  always pauses before the final submit action.
- `scripts/track_applications.py` — CSV/JSON application tracker with
  duplicate-detection, stats, follow-up reminders, and an HTML dashboard.
- `scripts/due_diligence_report.py` — turns compiled company-background
  findings into a shareable Markdown/HTML report (basic info, legal risk,
  employee/social sentiment, red flags).
- `references/company_due_diligence.md` — per-source search-query templates
  (知乎/企查查/天眼查/裁判文书网/看准网/小红书/抖音) and how to weigh and
  present what comes back.
- `references/similar_projects.md` — survey of comparable open-source
  projects and what this skill deliberately borrowed vs. avoided from them.
```

## File: README.md
size: 6193
sha: 0ba88dc771614676019d4e055e11a43a60ad9f7d
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/README.md

````text
# job-application-assistant

**个人求职 AI Skill｜适用于 Claude / Codex**

*[English](README.en.md)*

<p align="center">
  <img src="docs/readme-hero.png" alt="job-application-assistant：个人求职 AI Skill" width="100%">
</p>

> **一句话看懂：** 让 AI 帮你**发现目标公司 → 投递前做背调 → 谨慎协助填写申请表 → 统一追踪所有投递**，而真正的提交始终由你本人确认。

这是一个给**个人求职者**使用的 Claude / Codex Skill，不是招聘 SaaS。  
没有服务器、没有账号体系、没有云同步；你的投递记录保存在本机 JSON 文件中。

---

## 30 秒看懂怎么用

### 1. 把 Skill 装进 Claude / Codex

- **Claude（桌面端 / Web）**：`Settings → Capabilities → Skills`，上传本项目文件夹或打包后的 `.skill` 文件。
- **Claude Code / Codex**：把本项目放入对应工具的 skills 目录。

### 2. 直接告诉它你想找什么岗位

例如：

```text
帮我寻找 AI Agent 开发相关岗位。
先找正在招聘的公司，优先给出官网招聘页；
准备投递前先做公司背景调查；
我确认后再协助填写申请表，并把投递记录加入看板。
```

### 3. Skill 按流程帮你推进

```text
找岗位
   ↓
确认目标公司
   ↓
公司背调
   ↓
决定是否继续
   ↓
辅助填写申请表
   ↓
你本人确认提交
   ↓
记录投递 + 后续跟进
```

**你不需要每天重复复制岗位信息、手动整理公司风险、再单独维护 Excel。**

---

## 它能帮你做什么

|  | 能力 | 你得到什么 |
|---|---|---|
| 🔎 | **找岗位** | 按岗位关键词寻找正在招聘的公司，并优先定位公司的**官方招聘页** |
| 🏢 | **先背调再投递** | 汇总财务健康度、法律/司法风险、员工口碑和社交媒体公开信息 |
| 📝 | **谨慎辅助填表** | 使用可见浏览器协助填写常见 ATS 表单，如 Greenhouse、Lever、Workday |
| 📊 | **统一追踪投递** | 集中记录公司、岗位、渠道、状态、风险标签与跟进提醒 |
| 🔁 | **避免重复投递** | 投递前检查是否已经申请过同一家公司 |
| 🔒 | **数据本地保存** | 无账号、无服务器、无云同步，求职记录保存在你的电脑里 |

---

## 真实输出长这样

### 投递记录看板

一眼查看所有投递过的公司、当前进度、渠道、更新时间，以及公司背调风险标签。

<p align="center">
  <img src="docs/dashboard-screenshot.png" alt="投递记录看板" width="100%">
</p>

### 公司背调报告

在决定是否继续投递或面试之前，把法律/司法风险、员工口碑和社交媒体公开评价集中到一份报告中。

<p align="center">
  <img src="docs/company-report-screenshot.png" alt="公司背景调查报告" width="78%">
</p>

两个页面都是自包含静态 HTML：不需要服务器，每次运行脚本都会根据你的本地数据重新生成。

---

## 为什么它不是“一键海投工具”

这个项目刻意保留了**人工确认**。

- **不会自动提交申请**：每一批真实投递都必须由你明确确认。
- **不会破解或绕过验证码**：遇到 CAPTCHA 会停止并把控制权交还给你。
- **不会编造简历经历**：不会为了“提高匹配度”虚构事实。
- **不会编造背调结论**：背调结果必须有公开来源。
- **不会无人值守连续海投**：流程中保留人工检查节点。

目标不是“投得越多越好”，而是让求职过程**更有信息、更可控、更容易持续跟进**。

---

## 安装

本项目以 **Claude Skill** 形式组织：

```text
SKILL.md
scripts/
references/
```

### Claude

1. 打开 Claude。
2. 进入 `Settings → Capabilities → Skills`。
3. 上传项目文件夹，或上传打包后的 `.skill` 文件。

### Claude Code / Codex

按照对应工具的 Skill 目录规范，把本项目放入 skills 目录即可。

---

## Python 依赖

投递追踪和报告生成：

- `scripts/track_applications.py`
- `scripts/due_diligence_report.py`

只依赖 Python 标准库。

岗位搜索与 ATS 表单辅助需要：

```bash
pip install -r requirements.txt
playwright install chromium
```

只有使用 `ats_form_filler.py` 时才需要安装 Chromium。

---

## 命令行快速体验

```bash
# 记录一条投递
python scripts/track_applications.py add \
  --company "Acme Corp" --role "Frontend Engineer" \
  --channel official_site --url "https://acme.com/careers/123" \
  --status submitted

# 检查是否已经投递过
python scripts/track_applications.py check --company "Acme Corp"

# 查看需要跟进的岗位
python scripts/track_applications.py followups --days 7

# 为公司关联背调报告
python scripts/due_diligence_report.py --input acme_findings.json \
  --out acme_report.html --format html

python scripts/track_applications.py diligence \
  --company "Acme Corp" --role "Frontend Engineer" \
  --risk medium --report acme_report.html --summary "1起劳动仲裁判决"

# 生成投递看板
python scripts/track_applications.py dashboard --out dashboard.html
```

完整命令参数见各脚本自带的 `--help` 和文件头部说明。

---

## 项目工作流与设计说明

完整分步工作流见 [`SKILL.md`](SKILL.md)。

各模块设计考虑、参考过的开源工具，以及**刻意没有采用的自动海投模式**，见 [`references/`](references/)。

---

## 数据与隐私

这是一个**个人本地求职工具**：

- 无服务器
- 无账号体系
- 无云同步
- 投递数据保存在本机 JSON
- 真实提交由用户本人确认

---

## Disclaimer

这是个人效率工具，不构成法律、财务或职业规划建议。

公司背调报告汇总的是公开信息和社交媒体评论。若某条信息会影响你的重要决定，例如具体诉讼、公司注册状态等，请在行动前到权威或一手来源再次核实。

你需要自行遵守与本工具交互的网站服务条款。

---

## License

MIT — see [LICENSE](LICENSE).

---

如果这个项目对你的求职流程有帮助，欢迎 **Star**、提交 **Issue**，或者分享你的使用反馈。
````

## File: scripts/ats_form_filler.py
size: 10423
sha: 170a61fa15a70b0d7f5757253f074f0129eb7089
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/scripts/ats_form_filler.py

```text
#!/usr/bin/env python3
"""
ats_form_filler.py

Playwright-based template for filling common ATS (Applicant Tracking System)
application forms. This is a REFERENCE IMPLEMENTATION, not a fire-and-forget
script — ATS forms vary, and this deliberately STOPS before the final submit
click so a human can review.

Requires:
    pip install playwright --break-system-packages
    playwright install chromium

Usage:
    python ats_form_filler.py \
        --url "https://boards.greenhouse.io/acme/jobs/12345" \
        --ats greenhouse \
        --name "Zhang Wei" --email "wei@example.com" --phone "+86 138..." \
        --resume "/path/to/resume.pdf" \
        --cover-letter "/path/to/cover_letter.pdf"

Behavior:
    1. Opens the page in a VISIBLE (headless=False) browser window by
       default — this is required so a human can see and manually solve
       any CAPTCHA/human-verification challenge the site throws up. Running
       headless hides the challenge entirely, which just looks like the
       script "getting stuck" with no way to respond. Pass --headless only
       if you specifically need a headless run and are confident the target
       form has no bot-check (rare).
    2. Detects/confirms the ATS type (or uses --ats if given).
    3. Checks for a CAPTCHA/anti-bot challenge on the page before filling
       anything (reCAPTCHA/hCaptcha iframe, Cloudflare challenge markers).
       If one is found, the script STOPS and waits at the terminal for you
       to solve it by hand in the visible window, then press Enter to
       continue. It never attempts to solve or bypass the challenge itself.
    4. Fills the known field set for that ATS from references/ats_platforms.md.
    5. Uploads resume/cover letter if fields exist.
    6. Takes a screenshot of the filled form and saves it locally.
    7. PAUSES — prints the screenshot path and a summary, and exits WITHOUT
       clicking submit. A human (or the calling agent, after explicit user
       go-ahead) must run the separate `--confirm-submit` pass to finish.
"""
import argparse
import sys
import time

try:
    from playwright.sync_api import sync_playwright
except ImportError:
    print(
        "Missing dep. Install with:\n"
        "    pip install playwright --break-system-packages\n"
        "    playwright install chromium\n",
        file=sys.stderr,
    )
    sys.exit(1)

# Field selector maps per ATS. These are best-effort and DOM structures
# change over time — verify against the live page and update as needed.
ATS_FIELD_MAP = {
    "greenhouse": {
        "name_first": "input#first_name",
        "name_last": "input#last_name",
        "email": "input#email",
        "phone": "input#phone",
        "resume_upload": "input[type=file][name='resume']",
        "cover_letter_upload": "input[type=file][name='cover_letter']",
        "submit_button": "input[type=submit], button#submit_app",
    },
    "lever": {
        "name": "input[name='name']",
        "email": "input[name='email']",
        "phone": "input[name='phone']",
        "resume_upload": "input[name='resume']",
        "submit_button": "button[type='submit']",
    },
    "workday": {
        # Workday is a heavily JS-driven multi-step wizard; selectors are
        # highly tenant-specific. Treat this as a starting point only —
        # you will likely need to record actual selectors per company via
        # the browser tool's inspector before this works reliably.
        "name_first": "input[data-automation-id='legalNameSection_firstName']",
        "name_last": "input[data-automation-id='legalNameSection_lastName']",
        "email": "input[data-automation-id='email']",
        "resume_upload": "input[data-automation-id='file-upload-input-ref']",
        "submit_button": "button[data-automation-id='bottom-navigation-next-button']",
    },
}

CAPTCHA_SELECTORS = [
    "iframe[src*='recaptcha']",
    "iframe[title*='recaptcha' i]",
    "iframe[src*='hcaptcha']",
    "div#challenge-form",             # Cloudflare challenge page
    "div.cf-turnstile",               # Cloudflare Turnstile
    "iframe[src*='turnstile']",
]

def detect_captcha(page) -> bool:
    for selector in CAPTCHA_SELECTORS:
        try:
            if page.locator(selector).count() > 0:
                return True
        except Exception:  # noqa: BLE001
            continue
    return False

def wait_for_manual_captcha_solve(page) -> None:
    """Never attempts to solve or bypass the challenge. Just makes sure a
    human can see it (headless=False is required for this to work) and
    pauses the script until they've dealt with it."""
    print(
        "\n🔒 A CAPTCHA / human-verification challenge was detected on this "
        "page.\nThe browser window is open — please solve it manually there, "
        "then come back to this terminal.\n"
    )
    input("Press Enter here once you've solved it and the page has moved on... ")

def detect_ats(url: str) -> str | None:
    if "greenhouse.io" in url:
        return "greenhouse"
    if "lever.co" in url:
        return "lever"
    if "myworkdayjobs.com" in url:
        return "workday"
    return None

def fill_form(page, ats: str, args) -> None:
    fields = ATS_FIELD_MAP.get(ats)
    if not fields:
        raise ValueError(
            f"No field map for ATS '{ats}'. Add one to ATS_FIELD_MAP after "
            "inspecting the live form, or fill manually."
        )

    def try_fill(selector_key, value):
        selector = fields.get(selector_key)
        if not selector or not value:
            return
        try:
            page.fill(selector, value, timeout=3000)
        except Exception as e:  # noqa: BLE001
            print(f"  (skip) could not fill {selector_key}: {e}", file=sys.stderr)

    if "name_first" in fields and args.name:
        first, *rest = args.name.split(" ", 1)
        try_fill("name_first", first)
        if rest:
            try_fill("name_last", rest[0])
    elif "name" in fields:
        try_fill("name", args.name)

    try_fill("email", args.email)
    try_fill("phone", args.phone)

    if args.resume and fields.get("resume_upload"):
        try:
            page.set_input_files(fields["resume_upload"], args.resume)
        except Exception as e:  # noqa: BLE001
            print(f"  (skip) resume upload failed: {e}", file=sys.stderr)

    if args.cover_letter and fields.get("cover_letter_upload"):
        try:
            page.set_input_files(fields["cover_letter_upload"], args.cover_letter)
        except Exception as e:  # noqa: BLE001
            print(f"  (skip) cover letter upload failed: {e}", file=sys.stderr)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", required=True)
    parser.add_argument("--ats", default="", help="greenhouse|lever|workday (auto-detected if omitted)")
    parser.add_argument("--name", default="")
    parser.add_argument("--email", default="")
    parser.add_argument("--phone", default="")
    parser.add_argument("--resume", default="")
    parser.add_argument("--cover-letter", default="")
    parser.add_argument("--screenshot-out", default="filled_form.png")
    parser.add_argument(
        "--confirm-submit",
        action="store_true",
        help="Only pass this after the user has explicitly reviewed and "
        "approved the filled form. Without it, the script never clicks submit.",
    )
    parser.add_argument(
        "--headless",
        action="store_true",
        help="Run without a visible window. NOT recommended: if the site "
        "shows a CAPTCHA, a headless run cannot be solved by a human. Only "
        "use this when you're confident the target form has no bot-check.",
    )
    args = parser.parse_args()

    ats = args.ats or detect_ats(args.url)
    if not ats:
        print(
            "Could not auto-detect ATS from URL. Pass --ats explicitly, or "
            "check references/ats_platforms.md for fingerprints.",
            file=sys.stderr,
        )
        sys.exit(1)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=args.headless)
        page = browser.new_page()
        page.goto(args.url, timeout=20000)
        time.sleep(1)

        if detect_captcha(page):
            if args.headless:
                print(
                    "CAPTCHA detected but running headless — a human can't "
                    "see it to solve it. Re-run without --headless.",
                    file=sys.stderr,
                )
                browser.close()
                sys.exit(1)
            wait_for_manual_captcha_solve(page)

        fill_form(page, ats, args)

        # Check again after filling — some forms only trigger the challenge
        # once fields are touched or on attempted submit.
        if detect_captcha(page):
            if args.headless:
                print(
                    "CAPTCHA appeared after filling, but running headless.",
                    file=sys.stderr,
                )
                browser.close()
                sys.exit(1)
            wait_for_manual_captcha_solve(page)

        page.screenshot(path=args.screenshot_out, full_page=True)
        print(f"Filled form screenshot saved to: {args.screenshot_out}")

        if args.confirm_submit:
            fields = ATS_FIELD_MAP[ats]
            submit_selector = fields.get("submit_button")
            if not submit_selector:
                print("No submit selector mapped for this ATS.", file=sys.stderr)
            else:
                page.click(submit_selector, timeout=5000)
                time.sleep(2)
                if detect_captcha(page):
                    print(
                        "CAPTCHA appeared right at submit — solve it manually "
                        "in the window, then check the page yourself to "
                        "confirm whether the application actually went "
                        "through (don't assume success).",
                    )
                    if not args.headless:
                        wait_for_manual_captcha_solve(page)
                else:
                    print("Submitted.")
        else:
            print(
                "NOT submitted — review the screenshot, then re-run with "
                "--confirm-submit once the user explicitly approves."
            )

        browser.close()

if __name__ == "__main__":
    main()
```

## File: scripts/due_diligence_report.py
size: 21903
sha: 0adbb896b6dfcbd2b062ad55653fe40d4f61de25
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/scripts/due_diligence_report.py

```text
#!/usr/bin/env python3
"""
due_diligence_report.py

Render a structured company due-diligence report (Markdown or HTML) from
findings JSON. This script does NOT search the web itself — see
references/company_due_diligence.md for the query templates. The calling
agent should run those searches (via web_search or similar), compile what
it finds into the JSON shape below, then call this script to produce a
clean, shareable report.

No network required here — purely local formatting, so it works in any
sandbox including ones without internet access.

Input JSON shape (all fields optional except "company"):
{
  "company": "Acme Corp",
  "role": "Frontend Engineer",                 // optional, ties it to a specific opening
  "risk": "medium",                             // optional: low|medium|high — shown as a
                                                 // stamp on the report; keep this in sync
                                                 // with the --risk you pass to
                                                 // track_applications.py diligence
  "basic_info": {
    "founded": "2015",
    "registered_capital": "5000万人民币",
    "legal_rep": "张三",
    "funding_stage": "C轮",
    "source": "企查查/天眼查"
  },
  "legal_risks": [
    {"type": "劳动争议判决", "summary": "2023年因未足额支付加班费被判赔偿",
     "source": "中国裁判文书网", "url": "https://...", "date": "2023-06"}
  ],
  "employee_reviews": [
    {"platform": "知乎", "sentiment": "negative",
     "summary": "多位回答提到加班较多，管理层沟通不畅", "url": "https://..."}
  ],
  "social_mentions": [
    {"platform": "小红书", "sentiment": "positive",
     "summary": "多篇入职体验贴反馈团队氛围不错", "url": "https://..."}
  ],
  "red_flags": ["近一年有2起劳动仲裁判决", "股权结构半年内变更3次"],
  "overall_notes": "整体口碑中性偏负面，建议面试时重点确认加班与薪酬发放节奏。"
}

Usage:
    python due_diligence_report.py --input acme_findings.json --out acme_report.md
    python due_diligence_report.py --input acme_findings.json --out acme_report.html --format html
"""
import argparse
import json
import re
import sys
from datetime import datetime

SENTIMENT_LABEL = {
    "positive": "正面 🟢",
    "negative": "负面 🔴",
    "neutral": "中性 ⚪",
}

def load_findings(path: str) -> dict:
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)

def render_markdown(data: dict) -> str:
    company = data.get("company", "未知公司")
    role = data.get("role", "")
    lines = [f"# {company} 背调报告", ""]
    if role:
        lines.append(f"_关联岗位：{role}_")
    lines.append(f"_生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M')}_")
    lines.append("")
    lines.append(
        "> 本报告基于公开信息（工商登记、裁判文书、社交媒体讨论）整理，"
        "仅供参考，不构成法律或财务建议；社交媒体评价为个人观点，"
        "请结合来源权威性自行判断。"
    )
    lines.append("")

    red_flags = data.get("red_flags", [])
    if red_flags:
        lines.append("## ⚠️ 重点风险提示")
        for flag in red_flags:
            lines.append(f"- {flag}")
        lines.append("")

    basic = data.get("basic_info", {})
    if basic:
        lines.append("## 基本信息")
        for key, label in [
            ("founded", "成立时间"),
            ("registered_capital", "注册资本"),
            ("legal_rep", "法定代表人"),
            ("funding_stage", "融资阶段"),
        ]:
            if basic.get(key):
                lines.append(f"- **{label}**：{basic[key]}")
        if basic.get("source"):
            lines.append(f"- _数据来源：{basic['source']}_")
        lines.append("")

    legal = data.get("legal_risks", [])
    if legal:
        lines.append("## 法律 / 司法风险")
        for item in legal:
            date = f"（{item['date']}）" if item.get("date") else ""
            lines.append(f"- **{item.get('type','')}**{date}：{item.get('summary','')}")
            if item.get("source") or item.get("url"):
                src = item.get("source", "")
                url = item.get("url", "")
                lines.append(f"  - 来源：{src} {url}".strip())
        lines.append("")
    else:
        lines.append("## 法律 / 司法风险")
        lines.append("未检索到明显司法风险记录（不代表不存在，建议自行到国家企业信用信息公示系统核实）。")
        lines.append("")

    reviews = data.get("employee_reviews", [])
    if reviews:
        lines.append("## 员工口碑")
        for item in reviews:
            sentiment = SENTIMENT_LABEL.get(item.get("sentiment", "neutral"), "")
            lines.append(f"- [{item.get('platform','')}] {sentiment} {item.get('summary','')}")
            if item.get("url"):
                lines.append(f"  - {item['url']}")
        lines.append("")

    social = data.get("social_mentions", [])
    if social:
        lines.append("## 社交媒体口碑（小红书/抖音等）")
        lines.append("_注意甄别官方营销内容与真实员工/用户反馈。_")
        for item in social:
            sentiment = SENTIMENT_LABEL.get(item.get("sentiment", "neutral"), "")
            lines.append(f"- [{item.get('platform','')}] {sentiment} {item.get('summary','')}")
            if item.get("url"):
                lines.append(f"  - {item['url']}")
        lines.append("")

    notes = data.get("overall_notes")
    if notes:
        lines.append("## 综合建议")
        lines.append(notes)
        lines.append("")

    return "\n".join(lines)

def render_html(data: dict) -> str:
    """Rendered as an "Editorial Intelligence" report — approved HTML demo:
    page-b-company-report.html. Serif display type, a prominent risk hero
    (not a small badge), numbered evidence sections, a closing verdict
    block. Same underlying `data` contract as before — only the rendering
    changed."""
    INK, MUTED, LINE, LINE_STRONG = "#101010", "#6E6E68", "#D5D4CE", "#AFAEA7"
    PAPER, PAGE_BG = "#FAFAF7", "#EDEDE9"
    RED, RED_SOFT, GREEN = "#B94335", "#F1DEDA", "#315C47"
    AMBER = "#8B6C1A"
    MONO = '"Cascadia Code","SFMono-Regular",Consolas,"Liberation Mono",monospace'
    SANS = 'Inter,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif'
    SERIF = '"Noto Serif SC","Source Han Serif SC","Songti SC",Georgia,serif'

    RISK_COLORS = {"low": GREEN, "medium": AMBER, "high": RED}
    RISK_SOFT = {"low": "#DDE7E0", "medium": "#EEE4CF", "high": RED_SOFT}
    RISK_LABEL_EN = {"low": "LOW", "medium": "MEDIUM", "high": "HIGH"}
    RISK_LABEL_ZH = {"low": "低", "medium": "中", "high": "高"}
    # Derived decision label from the risk field — a display transform of
    # existing data, not a new fact. No risk => no decision block (nothing
    # to derive it from).
    DECISION = {
        "low": ("PROCEED", "建议：可按正常节奏推进。"),
        "medium": ("PROCEED WITH CAUTION", "建议：可继续推进，但需重点核实下方红旗提示中的问题。"),
        "high": ("RECONSIDER", "建议：谨慎对待，最好先获得更多信息确认后再决定是否继续。"),
    }
    SENTIMENT_LABEL_EN = {"positive": "POSITIVE", "negative": "NEGATIVE", "neutral": "NEUTRAL"}
    SENTIMENT_CLASS = {"positive": "", "negative": "negative", "neutral": ""}

    company = data.get("company", "未知公司")
    role = data.get("role", "")
    risk = data.get("risk", "")

    def esc(s):
        return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

    # Risk hero — the report's single most important visual element.
    riskbox_html = ""
    if risk in RISK_COLORS:
        n_legal = len(data.get("legal_risks", []))
        n_red_flags = len(data.get("red_flags", []))
        n_negative = sum(
            1 for i in data.get("employee_reviews", []) + data.get("social_mentions", [])
            if i.get("sentiment") == "negative"
        )
        basis_parts = []
        if n_red_flags:
            basis_parts.append(f"{n_red_flags} 条重点风险提示")
        if n_legal:
            basis_parts.append(f"{n_legal} 条法律/司法记录")
        if n_negative:
            basis_parts.append(f"{n_negative} 条负面口碑")
        basis = "、".join(basis_parts) if basis_parts else "以下公开信息"
        riskbox_html = f'''<aside class="riskbox">
      <div class="label">OVERALL RISK</div>
      <div class="risk" style="color:{RISK_COLORS[risk]}">{RISK_LABEL_EN[risk]}</div>
      <div class="cn">综合风险：{RISK_LABEL_ZH[risk]}</div>
      <p>本判断基于{esc(basis)}综合得出，详见下方各节证据；请结合来源权威性自行判断，不作为最终结论。</p>
    </aside>'''

    # Red flags — existing field from before this UI pass. The approved
    # demo doesn't have an explicit slot for this, so it's folded into the
    # risk-hero basis text above AND kept as its own compact list here
    # (styled with the demo's own .tag language) so no data is dropped.
    red_flags = data.get("red_flags", [])
    red_flags_html = ""
    if red_flags:
        tags = "".join(f'<span class="tag high" style="margin:0 8px 8px 0;">{esc(f)}</span>' for f in red_flags)
        red_flags_html = f'<div class="disclaimer" style="border-top:none;"><div style="font:800 10px/1.2 {MONO};letter-spacing:.1em;color:{MUTED};text-transform:uppercase;margin-bottom:10px;">重点风险提示</div>{tags}</div>'

    # Lede / executive note — derived from the first sentence of
    # overall_notes (real data), not a separately-invented field.
    lede_html = ""
    notes = data.get("overall_notes", "")
    if notes:
        first_sentence = re.split(r"(?<=[。！])", notes.strip())[0]
        lede_html = f'''<section class="lede">
      <div class="index">EXECUTIVE NOTE</div>
      <p>{esc(first_sentence)}</p>
    </section>'''

    def section(num, tag, title, inner):
        return f'''<section class="section">
      <div class="section-num">{num}<span>{tag}</span></div>
      <div>
        <h2>{title}</h2>
        {inner}
      </div>
    </section>'''

    # 01 — basic info facts grid
    basic = data.get("basic_info", {})
    fact_defs = [
        ("founded", "Founded"), ("registered_capital", "Registered Capital"),
        ("legal_rep", "Legal Representative"), ("funding_stage", "Funding"),
    ]
    facts = [(label, basic[key]) for key, label in fact_defs if basic.get(key)]
    basic_section = ""
    if facts:
        facts_html = "".join(
            f'<div class="fact"><div class="k">{esc(k)}</div><div class="v">{esc(v)}</div></div>'
            for k, v in facts
        )
        source_note = (
            f'<div class="muted" style="font:600 11px/1.4 {MONO};margin-top:10px;">数据来源：{esc(basic["source"])}</div>'
            if basic.get("source") else ""
        )
        basic_section = section("01", "THE COMPANY", "基本信息", f'<div class="facts">{facts_html}</div>{source_note}')

    # 02 — legal / judicial risk signals
    legal = data.get("legal_risks", [])
    if legal:
        signal_rows = []
        for item in legal:
            src = ""
            if item.get("url"):
                src = f'<div class="source"><a href="{esc(item["url"])}" target="_blank">{esc(item.get("source","SOURCE"))} ↗</a></div>'
            elif item.get("source"):
                src = f'<div class="source">{esc(item["source"])}</div>'
            signal_rows.append(f'''<div class="signal">
        <div class="tagwrap"><span class="tag high">RISK</span></div>
        <div class="date">{esc(item.get("date","—"))}</div>
        <div class="summary"><h3>{esc(item.get("type",""))}</h3><p>{esc(item.get("summary",""))}</p></div>
        {src}
      </div>''')
        legal_inner = "\n".join(signal_rows)
    else:
        legal_inner = '<p class="muted">未检索到明显司法风险记录（不代表不存在，建议自行到国家企业信用信息公示系统核实）。</p>'
    legal_section = section("02", "LEGAL SIGNALS", "法律与司法风险", legal_inner)

    def quote_block(item):
        sentiment = item.get("sentiment", "neutral")
        link = f'<a href="{esc(item["url"])}" target="_blank">查看原文 ↗</a>' if item.get("url") else ""
        return f'''<div class="quote">
        <div class="source-line"><span>{esc(item.get("platform",""))}</span>
        <span class="sentiment {SENTIMENT_CLASS.get(sentiment,"")}">{SENTIMENT_LABEL_EN.get(sentiment,"")}</span></div>
        <blockquote>{esc(item.get("summary",""))}</blockquote>
        <div class="source-line"><span class="muted">摘要来自公开来源，需注意个体样本偏差。</span>{link}</div>
      </div>'''

    reviews = data.get("employee_reviews", [])
    reviews_section = ""
    if reviews:
        reviews_section = section("03", "EMPLOYEE VOICE", "员工口碑", "\n".join(quote_block(i) for i in reviews))

    social = data.get("social_mentions", [])
    social_section = ""
    if social:
        social_section = section("04", "SOCIAL SIGNALS", "社交媒体口碑", "\n".join(quote_block(i) for i in social))

    # Verdict — uses the real overall_notes field; decision block derived
    # from the risk field (hidden if no risk was provided, since there's
    # nothing to derive it from).
    verdict_html = ""
    if notes or risk in DECISION:
        decision_html = ""
        if risk in DECISION:
            big, small = DECISION[risk]
            decision_html = f'<div class="decision"><div class="big" style="color:{RISK_COLORS[risk]}">{big}</div><div class="small">{esc(small)}</div></div>'
        verdict_html = f'''<section class="verdict">
      <div>
        <div class="kicker">THE VERDICT</div>
        <h2>综合建议</h2>
        <p>{esc(notes) if notes else "暂无综合建议，请结合以上信息自行判断。"}</p>
      </div>
      {decision_html}
    </section>'''

    return f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{esc(company)} — 公司背调报告</title>
<style>
:root{{
  --paper:{PAPER}; --ink:{INK}; --muted:{MUTED}; --line:{LINE}; --line-strong:{LINE_STRONG};
  --red:{RED}; --red-soft:{RED_SOFT}; --green:{GREEN};
  --mono:{MONO}; --sans:{SANS}; --serif:{SERIF};
}}
*{{box-sizing:border-box}}
html{{background:{PAGE_BG};color:var(--ink)}}
body{{margin:0;font-family:var(--sans);background:{PAGE_BG}}}
a{{color:inherit;text-decoration:none;border-bottom:1px solid currentColor}}
.page{{max-width:1180px;margin:26px auto;background:var(--paper);min-height:100vh;padding:38px 54px 72px;box-shadow:0 8px 30px rgba(0,0,0,.04)}}
.masthead{{display:flex;justify-content:space-between;gap:24px;border-bottom:2px solid var(--ink);padding-bottom:16px}}
.brand{{font:800 12px/1 var(--mono);letter-spacing:.15em;text-transform:uppercase}}
.issue{{text-align:right;font:600 11px/1.55 var(--mono);color:var(--muted)}}
.hero{{display:grid;grid-template-columns:1.6fr .8fr;gap:42px;padding:42px 0 34px;border-bottom:1px solid var(--line-strong)}}
.kicker{{font:800 11px/1 var(--mono);letter-spacing:.13em;color:var(--muted);text-transform:uppercase;margin-bottom:18px}}
h1{{font-family:var(--serif);font-size:54px;line-height:1.04;letter-spacing:-.045em;margin:0;max-width:720px}}
.subhead{{font-size:16px;color:var(--muted);margin-top:16px}}
.riskbox{{align-self:start;border:1px solid var(--ink);padding:18px 20px 20px;position:sticky;top:24px}}
.riskbox .label{{font:800 10px/1 var(--mono);letter-spacing:.12em;color:var(--muted)}}
.riskbox .risk{{font:800 50px/.95 var(--mono);letter-spacing:-.05em;margin-top:18px}}
.riskbox .cn{{font-family:var(--serif);font-weight:700;font-size:22px;margin-top:8px}}
.riskbox p{{font-size:12px;line-height:1.65;color:var(--muted);margin:20px 0 0;padding-top:14px;border-top:1px solid var(--line)}}
.disclaimer{{padding:13px 0;border-bottom:1px solid var(--line);font-size:12px;color:var(--muted);line-height:1.6}}
.lede{{display:grid;grid-template-columns:160px 1fr;gap:28px;padding:34px 0 6px}}
.lede .index{{font:800 12px/1 var(--mono);letter-spacing:.08em}}
.lede p{{font-family:var(--serif);font-size:23px;line-height:1.6;margin:0;max-width:760px}}
.section{{display:grid;grid-template-columns:160px 1fr;gap:28px;padding:40px 0;border-top:1px solid var(--line-strong)}}
.section-num{{font:800 34px/1 var(--mono);letter-spacing:-.05em}}
.section-num span{{display:block;font:800 10px/1.3 var(--mono);letter-spacing:.12em;color:var(--muted);margin-top:8px}}
.section h2{{font-family:var(--serif);font-size:32px;line-height:1.1;margin:0 0 22px;letter-spacing:-.025em}}
.muted{{color:var(--muted)}}
.facts{{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid var(--ink);border-bottom:1px solid var(--ink)}}
.fact{{padding:18px 16px;border-right:1px solid var(--line)}}.fact:last-child{{border-right:0}}
.fact .k{{font:800 10px/1.2 var(--mono);letter-spacing:.08em;color:var(--muted);text-transform:uppercase}}
.fact .v{{font-family:var(--serif);font-size:22px;margin-top:10px}}
.signal{{display:grid;grid-template-columns:110px 100px 1fr 140px;gap:16px;padding:18px 0;border-top:1px solid var(--line);align-items:start}}
.signal:first-of-type{{border-top:1px solid var(--ink)}}
.tag{{font:800 10px/1 var(--mono);padding:5px 6px;border:1px solid currentColor;display:inline-block}}
.tag.high{{color:var(--red);background:var(--red-soft)}}
.signal .date{{font:700 11px/1.4 var(--mono);color:var(--muted)}}
.signal h3{{font-size:14px;margin:0 0 6px}}
.signal p{{font-size:13px;line-height:1.7;color:#3D3D39;margin:0}}
.source{{font:800 10px/1.2 var(--mono);text-align:right}}
.source a{{border-bottom:0}}.source a:hover{{text-decoration:underline}}
.quote{{padding:24px 0;border-top:1px solid var(--ink)}}.quote:first-of-type{{border-top:0}}
.quote .source-line{{display:flex;justify-content:space-between;gap:16px;font:800 10px/1.3 var(--mono);letter-spacing:.05em;color:var(--muted)}}
.quote blockquote{{font-family:var(--serif);font-size:19px;line-height:1.7;margin:16px 0 10px}}
.sentiment{{font:800 10px/1 var(--mono)}}.sentiment.negative{{color:var(--red)}}
.verdict{{display:grid;grid-template-columns:1fr 220px;gap:28px;background:#EFEFEA;border-top:2px solid var(--ink);padding:28px 30px}}
.verdict h2{{margin:0 0 14px}}.verdict p{{font-family:var(--serif);font-size:19px;line-height:1.75;margin:0}}
.decision{{border-left:1px solid var(--line-strong);padding-left:22px}}
.decision .big{{font:800 26px/1.15 var(--mono)}}
.decision .small{{font-size:12px;color:var(--muted);line-height:1.6;margin-top:12px}}
.footer{{display:flex;justify-content:space-between;gap:18px;padding-top:24px;margin-top:44px;border-top:1px solid var(--ink);font:600 10px/1.5 var(--mono);color:var(--muted)}}
@media (max-width:860px){{
  .page{{margin:0;padding:28px 20px 52px}}
  .hero{{grid-template-columns:1fr}}
  .riskbox{{position:static}}
  .lede,.section{{grid-template-columns:1fr}}
  .lede .index{{margin-bottom:-12px}}
  .facts{{grid-template-columns:repeat(2,1fr)}}
  .fact:nth-child(2){{border-right:0}}
  .fact:nth-child(-n+2){{border-bottom:1px solid var(--line)}}
  .signal{{grid-template-columns:90px 1fr}}
  .signal .date{{grid-column:1/2}}.signal .summary{{grid-column:2/3}}
  .signal .source{{grid-column:2/3;text-align:left}}.signal .tagwrap{{grid-column:1/2}}
  .verdict{{grid-template-columns:1fr}}
  .decision{{border-left:0;border-top:1px solid var(--line-strong);padding:18px 0 0}}
  .footer{{flex-direction:column}}h1{{font-size:42px}}
}}
</style>
</head>
<body>
<article class="page">
  <header class="masthead">
    <div class="brand">Job Application Assistant / Company Intelligence</div>
    <div class="issue">生成时间 {datetime.now().strftime('%Y.%m.%d / %H:%M')}<br>PERSONAL RESEARCH FILE</div>
  </header>

  <section class="hero">
    <div>
      <div class="kicker">Company Background Report</div>
      <h1>{esc(company)}</h1>
      {f'<div class="subhead">关联岗位：{esc(role)}</div>' if role else ''}
    </div>
    {riskbox_html}
  </section>

  <div class="disclaimer">免责声明：本报告基于公开来源与平台信息汇总，仅用于个人求职决策参考，不构成法律、财务或投资建议。公开信息可能存在延迟、缺失或上下文不完整。</div>
  {red_flags_html}
  {lede_html}
  {basic_section}
  {legal_section}
  {reviews_section}
  {social_section}
  {verdict_html}

  <footer class="footer"><span>PERSONAL USE ONLY · PUBLIC-SOURCE RESEARCH</span><span>JOB-APPLICATION-ASSISTANT / COMPANY DOSSIER</span></footer>
</article>
</body>
</html>"""

def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input", required=True, help="Path to findings JSON")
    parser.add_argument("--out", required=True, help="Output file path")
    parser.add_argument("--format", choices=["markdown", "html"], default="markdown")
    args = parser.parse_args()

    try:
        data = load_findings(args.input)
    except FileNotFoundError:
        print(f"Input file not found: {args.input}", file=sys.stderr)
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {args.input}: {e}", file=sys.stderr)
        sys.exit(1)

    if not data.get("company"):
        print("Findings JSON must include a 'company' field.", file=sys.stderr)
        sys.exit(1)

    content = render_html(data) if args.format == "html" else render_markdown(data)
    with open(args.out, "w", encoding="utf-8") as f:
        f.write(content)
    print(f"Report written to {args.out}")

if __name__ == "__main__":
    main()
```

## File: scripts/find_career_page.py
size: 4972
sha: 60b7ad817faf69fa8283c11b214b675b55ae8ccd
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/scripts/find_career_page.py

```text
#!/usr/bin/env python3
"""
find_career_page.py

Given a company name, try to find its OFFICIAL careers/jobs page (as opposed
to a third-party aggregator mirror of the same listing). REQUIRES NETWORK.

Usage:
    python find_career_page.py "Acme Corp"
    python find_career_page.py "Acme Corp" --homepage https://acme.com

Strategy:
1. If a homepage URL isn't given, search for "<company> official site" and
   take the top plausible result (heuristic: domain looks like the company
   name, not a news/wiki/social aggregator).
2. Probe common careers paths on that domain (/careers, /jobs, /about/careers,
   /careers/jobs, /en/careers, etc).
3. Also check for well-known ATS subdomains (boards.greenhouse.io/<company>,
   jobs.lever.co/<company>, <company>.wd1.myworkdayjobs.com, etc) since many
   companies host applications there while *linking* from their own domain —
   that's still their official channel, just hosted by a vendor.
4. Return the first working candidate with a confidence note; return all
   candidates checked so the user/agent can pick if the top one is wrong.
"""
import argparse
import sys
from urllib.parse import urlparse

try:
    import requests
except ImportError:
    print(
        "Missing deps. Install with: pip install requests --break-system-packages",
        file=sys.stderr,
    )
    sys.exit(1)

HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; job-application-assistant/1.0)"}
TIMEOUT = 8

COMMON_CAREER_PATHS = [
    "/careers",
    "/jobs",
    "/about/careers",
    "/company/careers",
    "/en/careers",
    "/careers/jobs",
    "/join-us",
    "/work-with-us",
    "/zh/careers",
    "/about-us/careers",
]

ATS_SUBDOMAIN_PATTERNS = [
    "https://boards.greenhouse.io/{slug}",
    "https://jobs.lever.co/{slug}",
    "https://{slug}.wd1.myworkdayjobs.com",
    "https://{slug}.wd5.myworkdayjobs.com",
    "https://apply.workable.com/{slug}",
    "https://{slug}.bamboohr.com/jobs",
    "https://{slug}.recruitee.com",
]

def slugify(name: str) -> str:
    return "".join(c.lower() for c in name if c.isalnum())

def probe(url: str) -> bool:
    try:
        resp = requests.head(
            url, headers=HEADERS, timeout=TIMEOUT, allow_redirects=True
        )
        if resp.status_code == 405:  # some servers reject HEAD
            resp = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
        return resp.status_code < 400
    except requests.RequestException:
        return False

def guess_homepage(company: str) -> str | None:
    """
    Best-effort: try the obvious <slug>.com first. For a robust answer,
    prefer resolving this via a real web_search tool in the calling agent
    (e.g. Claude's web_search) and passing --homepage explicitly — this
    local guess is only a fallback.
    """
    slug = slugify(company)
    for tld in (".com", ".io", ".ai", ".co"):
        candidate = f"https://www.{slug}{tld}"
        if probe(candidate):
            return candidate
    return None

def find_career_candidates(homepage: str, company: str) -> list[dict]:
    candidates = []
    domain = urlparse(homepage).netloc
    for path in COMMON_CAREER_PATHS:
        url = f"https://{domain}{path}"
        if probe(url):
            candidates.append(
                {"url": url, "confidence": "high", "reason": "on company domain"}
            )

    slug = slugify(company)
    for pattern in ATS_SUBDOMAIN_PATTERNS:
        url = pattern.format(slug=slug)
        if probe(url):
            candidates.append(
                {
                    "url": url,
                    "confidence": "medium",
                    "reason": "known ATS vendor, guessed slug — verify it's this company",
                }
            )
    return candidates

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("company", help="Company name")
    parser.add_argument(
        "--homepage",
        default="",
        help="Known homepage URL (skip guessing). Recommended: resolve this "
        "via a real search tool first for accuracy.",
    )
    args = parser.parse_args()

    homepage = args.homepage or guess_homepage(args.company)
    if not homepage:
        print(
            f"Could not guess a homepage for '{args.company}'. "
            "Pass --homepage explicitly after finding it via web search.",
            file=sys.stderr,
        )
        sys.exit(1)

    print(f"Homepage: {homepage}")
    candidates = find_career_candidates(homepage, args.company)
    if not candidates:
        print("No careers page found via common paths or known ATS vendors.")
        print(
            "Fall back to: (1) the aggregator listing found earlier, or "
            "(2) a manual web_search for '<company> careers official site'."
        )
        return

    print("Candidate career pages (best first):")
    for c in candidates:
        print(f"  [{c['confidence']}] {c['url']}  ({c['reason']})")

if __name__ == "__main__":
    main()
```

## File: scripts/search_target_companies.py
size: 7603
sha: 5b22ac1f6a865a57099d399518149f3aa3f69072
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/scripts/search_target_companies.py

```text
#!/usr/bin/env python3
"""
search_target_companies.py

Search job aggregators for companies currently hiring for a given role, and
return a deduplicated list of {company, title, location, posting_url, source}.

REQUIRES NETWORK ACCESS. This sandbox has network disabled for bash_tool, so
this script is written for the *user's own* Claude Code / Codex environment
(or any environment with outbound internet). If run here it will fail fast
with a clear message rather than hanging.

Usage:
    python search_target_companies.py "前端工程师" --location "上海" --limit 30
    python search_target_companies.py "Product Manager" --location "Remote" \
        --sources linkedin,indeed

Design notes:
- This does NOT scrape logged-in-only pages or bypass any paywall/CAPTCHA.
  Every source below has a public search results page usable without login;
  if a site changes its markup or starts requiring login, that source will
  simply return zero results and should be swapped for an official API where
  one exists (e.g. GitHub Jobs-style feeds, greenhouse.io's public job board
  JSON endpoints, a licensed job-board API key, etc).
- Prefer official APIs over HTML scraping wherever the target site offers one
  (Greenhouse's `boards-api.greenhouse.io/v1/boards/<token>/jobs` is a good
  example of a clean, ToS-friendly public endpoint).
"""
import argparse
import json
import sys
import time
from dataclasses import dataclass, asdict
from urllib.parse import quote

try:
    import requests
    from bs4 import BeautifulSoup
except ImportError:
    print(
        "Missing deps. Install with:\n"
        "    pip install requests beautifulsoup4 --break-system-packages\n",
        file=sys.stderr,
    )
    sys.exit(1)

HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (compatible; job-application-assistant/1.0; "
        "+for personal job-search use)"
    )
}
TIMEOUT = 10

@dataclass
class Posting:
    company: str
    title: str
    location: str
    posting_url: str
    source: str

def _get(url, params=None):
    resp = requests.get(url, headers=HEADERS, params=params, timeout=TIMEOUT)
    resp.raise_for_status()
    return resp

def search_indeed(role: str, location: str, limit: int) -> list[Posting]:
    """Public Indeed search results page (no login required)."""
    out: list[Posting] = []
    try:
        url = "https://www.indeed.com/jobs"
        resp = _get(url, params={"q": role, "l": location})
        soup = BeautifulSoup(resp.text, "html.parser")
        cards = soup.select("div.job_seen_beacon") or soup.select(
            "a.tapItem"
        )
        for card in cards[:limit]:
            company_el = card.select_one(".companyName")
            title_el = card.select_one("h2.jobTitle span") or card.select_one(
                ".jobTitle"
            )
            loc_el = card.select_one(".companyLocation")
            link_el = card.select_one("a")
            if not (company_el and title_el and link_el):
                continue
            href = link_el.get("href", "")
            full_url = (
                href if href.startswith("http") else f"https://www.indeed.com{href}"
            )
            out.append(
                Posting(
                    company=company_el.get_text(strip=True),
                    title=title_el.get_text(strip=True),
                    location=loc_el.get_text(strip=True) if loc_el else location,
                    posting_url=full_url,
                    source="indeed",
                )
            )
    except Exception as e:  # noqa: BLE001
        print(f"[indeed] search failed: {e}", file=sys.stderr)
    return out

def search_linkedin(role: str, location: str, limit: int) -> list[Posting]:
    """
    LinkedIn's public job-search guest endpoint. LinkedIn aggressively rate
    limits / blocks scraping — treat this as best-effort, low-volume, and
    switch to LinkedIn's official Talent/Jobs API if you need reliability.
    """
    out: list[Posting] = []
    try:
        url = "https://www.linkedin.com/jobs-guest/jobs/api/seeMoreJobPostings/search"
        resp = _get(
            url,
            params={
                "keywords": role,
                "location": location,
                "start": 0,
            },
        )
        soup = BeautifulSoup(resp.text, "html.parser")
        cards = soup.select("li")
        for card in cards[:limit]:
            title_el = card.select_one(".base-search-card__title")
            company_el = card.select_one(".base-search-card__subtitle")
            loc_el = card.select_one(".job-search-card__location")
            link_el = card.select_one("a.base-card__full-link")
            if not (title_el and company_el and link_el):
                continue
            out.append(
                Posting(
                    company=company_el.get_text(strip=True),
                    title=title_el.get_text(strip=True),
                    location=loc_el.get_text(strip=True) if loc_el else location,
                    posting_url=link_el.get("href", "").split("?")[0],
                    source="linkedin",
                )
            )
    except Exception as e:  # noqa: BLE001
        print(f"[linkedin] search failed: {e}", file=sys.stderr)
    return out

def search_zhaopin_cn(role: str, location: str, limit: int) -> list[Posting]:
    """
    Placeholder for a China-focused source (智联招聘 / 猎聘 / BOSS直聘).
    These sites require signed API params or app-only endpoints and change
    frequently, so wire this up against whichever one you have legitimate
    API access to, or use their official open-platform APIs if available.
    """
    print(
        "[zhaopin_cn] not implemented — plug in an official API "
        "(e.g. 智联招聘开放平台) or a licensed job-board data provider here.",
        file=sys.stderr,
    )
    return []

SOURCES = {
    "indeed": search_indeed,
    "linkedin": search_linkedin,
    "zhaopin_cn": search_zhaopin_cn,
}

def dedupe(postings: list[Posting]) -> list[Posting]:
    seen = set()
    result = []
    for p in postings:
        key = (p.company.strip().lower(), p.title.strip().lower())
        if key in seen:
            continue
        seen.add(key)
        result.append(p)
    return result

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("role", help="Job title/role to search for")
    parser.add_argument("--location", default="", help="City / 'Remote' / etc.")
    parser.add_argument("--limit", type=int, default=25, help="Max results per source")
    parser.add_argument(
        "--sources",
        default="indeed,linkedin",
        help="Comma-separated source list: " + ",".join(SOURCES.keys()),
    )
    parser.add_argument("--out", default="", help="Write JSON results to this file")
    args = parser.parse_args()

    all_postings: list[Posting] = []
    for name in args.sources.split(","):
        name = name.strip()
        fn = SOURCES.get(name)
        if not fn:
            print(f"Unknown source: {name}", file=sys.stderr)
            continue
        all_postings.extend(fn(args.role, args.location, args.limit))
        time.sleep(1)  # be polite between sources

    all_postings = dedupe(all_postings)

    payload = [asdict(p) for p in all_postings]
    text = json.dumps(payload, ensure_ascii=False, indent=2)
    if args.out:
        with open(args.out, "w", encoding="utf-8") as f:
            f.write(text)
        print(f"Wrote {len(payload)} postings to {args.out}")
    else:
        print(text)

if __name__ == "__main__":
    main()
```

## File: scripts/track_applications.py
size: 24344
sha: b21544e370704b312fdc14f7353e8dc2c20ba69c
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/scripts/track_applications.py

```text
#!/usr/bin/env python3
"""
track_applications.py

Local tracker for job applications — no network required. Stores records in
a JSON file (default: ./applications.json). No cloud upload, no account
needed: everything stays on the user's machine (same privacy stance as most
open-source job-apply tools — see references/similar_projects.md).

Usage:
    # Add/update a record (adding an existing company+role updates it and
    # warns you it's a duplicate, so you don't double-apply by accident)
    python track_applications.py add \
        --company "Acme Corp" --role "Frontend Engineer" \
        --channel official_site --ats greenhouse \
        --url "https://boards.greenhouse.io/acme/jobs/12345" \
        --status submitted

    # List everything / filter by status
    python track_applications.py list
    python track_applications.py list --status pending

    # Quick summary counts (by status / channel / this week)
    python track_applications.py stats

    # Which submitted applications have had no status change in N days
    # (a candidate for a follow-up email)
    python track_applications.py followups --days 10

    # Self-contained HTML dashboard you can open in a browser
    python track_applications.py dashboard --out dashboard.html

    # Export to CSV (e.g. to import into Google Sheets/Excel)
    python track_applications.py export --out applications.csv

    # Check before applying whether you already have a record for a company
    # (mirrors the "skip already-applied companies" pattern from
    # Auto_job_applier_linkedIn)
    python track_applications.py check --company "Acme Corp"

    # Attach a due-diligence finding (from due_diligence_report.py) to a
    # company's record so it shows up as a risk badge + link in the
    # dashboard, instead of living in a separate, disconnected file
    python track_applications.py diligence \
        --company "Acme Corp" --role "Frontend Engineer" \
        --risk medium --report acme_report.html \
        --summary "1起劳动仲裁判决，知乎评价偏负面，小红书入职体验尚可"
"""
import argparse
import csv
import json
import os
import sys
from collections import Counter
from datetime import datetime, timezone, timedelta

DB_PATH_DEFAULT = "applications.json"

STATUS_ORDER = ["pending", "filled", "submitted", "interview", "offer", "rejected"]

# Design tokens — sourced directly from the approved HTML demo
# (page-a-applications.html / page-b-company-report.html). These are now
# the visual source of truth; see SKILL.md / this file's cmd_dashboard()
# docstring for the design brief.
BG = "#F2F2EF"
PANEL = "#F8F8F5"
INK = "#161616"
MUTED = "#6F706B"
LINE = "#CBCBC5"
LINE_STRONG = "#AFAFA8"
GREEN = "#315C47"
GREEN_SOFT = "#DDE7E0"
RED = "#B94335"
RED_SOFT = "#F1DEDA"
AMBER = "#9B6B20"
AMBER_SOFT = "#EEE4CF"
BLUE = "#34506E"
BLUE_SOFT = "#DEE6ED"
MONO = '"Cascadia Code","SFMono-Regular",Consolas,"Liberation Mono",monospace'
SANS = 'Inter,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif'

STATUS_COLORS = {
    "pending": MUTED,
    "filled": BLUE,
    "submitted": GREEN,
    "interview": BLUE,
    "offer": GREEN,
    "rejected": "#777777",
}
STATUS_LABEL_ZH = {
    "pending": "待处理",
    "filled": "已填表",
    "submitted": "已投递",
    "interview": "面试中",
    "offer": "已获Offer",
    "rejected": "已拒绝",
}
RISK_COLORS = {"low": GREEN, "medium": AMBER, "high": RED}
RISK_SOFT = {"low": GREEN_SOFT, "medium": AMBER_SOFT, "high": RED_SOFT}
RISK_LABEL_ZH = {"low": "低风险", "medium": "中风险", "high": "高风险"}
RISK_LABEL_EN = {"low": "LOW", "medium": "MED", "high": "HIGH"}

def load_db(path: str) -> list[dict]:
    if not os.path.exists(path):
        return []
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)

def save_db(path: str, records: list[dict]) -> None:
    with open(path, "w", encoding="utf-8") as f:
        json.dump(records, f, ensure_ascii=False, indent=2)

def _key(company: str, role: str) -> tuple[str, str]:
    return (company.strip().lower(), role.strip().lower())

def cmd_add(args):
    records = load_db(args.db)
    key_fields = _key(args.company, args.role)
    for r in records:
        if _key(r["company"], r["role"]) == key_fields:
            print(
                f"⚠️  Duplicate: you already have a record for "
                f"{r['company']} / {r['role']} (current status: {r.get('status')})."
                f" Updating it instead of creating a new one."
            )
            r.update(
                {
                    "channel": args.channel or r.get("channel"),
                    "ats": args.ats or r.get("ats"),
                    "url": args.url or r.get("url"),
                    "status": args.status or r.get("status"),
                    "notes": args.notes or r.get("notes", ""),
                    "updated_at": datetime.now(timezone.utc).isoformat(),
                }
            )
            save_db(args.db, records)
            print(f"Updated existing record for {args.company} / {args.role}")
            return

    now = datetime.now(timezone.utc).isoformat()
    records.append(
        {
            "company": args.company,
            "role": args.role,
            "channel": args.channel,
            "ats": args.ats,
            "url": args.url,
            "status": args.status or "pending",
            "notes": args.notes,
            "created_at": now,
            "updated_at": now,
        }
    )
    save_db(args.db, records)
    print(f"Added record for {args.company} / {args.role}")

def cmd_check(args):
    """Look up whether a company already has a record — call this before
    starting a new application to avoid re-applying to the same company."""
    records = load_db(args.db)
    matches = [
        r for r in records if args.company.strip().lower() in r["company"].strip().lower()
    ]
    if not matches:
        print(f"No existing record for '{args.company}' — clear to apply.")
        return
    print(f"Found {len(matches)} existing record(s) for '{args.company}':")
    for r in matches:
        print(f"  - {r['role']}  [{r.get('status')}]  {r.get('url','')}")

def cmd_diligence(args):
    """Attach a due-diligence summary (produced by due_diligence_report.py)
    to an existing company/role record so the dashboard can show a risk
    badge + link instead of leaving the report as a disconnected file. If
    no matching record exists yet, creates a minimal one — useful when
    you're vetting a company before deciding to apply at all."""
    records = load_db(args.db)
    key_fields = _key(args.company, args.role)
    now = datetime.now(timezone.utc).isoformat()
    due_diligence = {
        "risk": args.risk,
        "report": args.report,
        "summary": args.summary,
        "checked_at": now,
    }
    for r in records:
        if _key(r["company"], r["role"]) == key_fields:
            r["due_diligence"] = due_diligence
            r["updated_at"] = now
            save_db(args.db, records)
            print(f"Attached due-diligence info to {args.company} / {args.role}")
            return

    records.append(
        {
            "company": args.company,
            "role": args.role,
            "channel": "",
            "ats": "",
            "url": "",
            "status": "pending",
            "notes": "",
            "created_at": now,
            "updated_at": now,
            "due_diligence": due_diligence,
        }
    )
    save_db(args.db, records)
    print(
        f"No existing record for {args.company} / {args.role} — created one "
        f"with the due-diligence info attached."
    )

def cmd_list(args):
    records = load_db(args.db)
    if args.status:
        records = [r for r in records if r.get("status") == args.status]
    if not records:
        print("No matching records.")
        return
    for r in records:
        print(
            f"- [{r.get('status','?'):10}] {r['company']:<25} {r['role']:<30} "
            f"({r.get('channel','?')}/{r.get('ats','-')})  {r.get('url','')}"
        )

def cmd_stats(args):
    records = load_db(args.db)
    if not records:
        print("No records yet.")
        return

    total = len(records)
    by_status = Counter(r.get("status", "unknown") for r in records)
    by_channel = Counter(r.get("channel", "unknown") or "unknown" for r in records)

    one_week_ago = datetime.now(timezone.utc) - timedelta(days=7)
    this_week = sum(
        1
        for r in records
        if _parse_dt(r.get("created_at")) and _parse_dt(r.get("created_at")) >= one_week_ago
    )

    print(f"Total applications tracked: {total}")
    print(f"Added in the last 7 days:   {this_week}")
    print("\nBy status:")
    for status in STATUS_ORDER:
        if by_status.get(status):
            print(f"  {status:10} {by_status[status]}")
    for status, count in by_status.items():
        if status not in STATUS_ORDER:
            print(f"  {status:10} {count}")
    print("\nBy channel:")
    for channel, count in by_channel.most_common():
        print(f"  {channel:15} {count}")

def _parse_dt(s):
    if not s:
        return None
    try:
        return datetime.fromisoformat(s)
    except ValueError:
        return None

def _stale_submitted(records, days):
    """Shared by cmd_followups (CLI) and cmd_dashboard (follow-up notice bar)
    so the "needs a follow-up" rule lives in exactly one place."""
    cutoff = datetime.now(timezone.utc) - timedelta(days=days)
    stale = []
    for r in records:
        if r.get("status") != "submitted":
            continue
        updated = _parse_dt(r.get("updated_at"))
        if updated and updated <= cutoff:
            days_ago = (datetime.now(timezone.utc) - updated).days
            stale.append((days_ago, r))
    stale.sort(reverse=True)
    return stale

def cmd_followups(args):
    """Applications in 'submitted' status that haven't been updated in
    --days days — good candidates for a polite follow-up message."""
    records = load_db(args.db)
    stale = _stale_submitted(records, args.days)
    if not stale:
        print(f"No submitted applications older than {args.days} days without an update.")
        return
    print(f"Applications with no update for {args.days}+ days (follow-up candidates):")
    for days_ago, r in stale:
        print(f"  - {r['company']} / {r['role']}  ({days_ago} days ago)  {r.get('url','')}")

def cmd_export(args):
    records = load_db(args.db)
    if not records:
        print("Nothing to export.")
        return
    fields = [
        "company",
        "role",
        "channel",
        "ats",
        "url",
        "status",
        "notes",
        "created_at",
        "updated_at",
    ]
    with open(args.out, "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        for r in records:
            writer.writerow({k: r.get(k, "") for k in fields})
    print(f"Exported {len(records)} records to {args.out}")

def cmd_dashboard(args):
    """Self-contained HTML dashboard — "Personal Job Ops Console" visual
    direction (approved HTML demo: page-a-applications.html). Industrial/
    terminal feel: horizontal metric strip (not KPI cards), dense scannable
    rows, monospace for numbers/labels, hairline borders only. No JS
    framework, no network calls — open directly in a browser.

    Data contract is unchanged from the previous version — this function
    only changes how the same `records` are rendered.
    """
    records = load_db(args.db)
    total = len(records)
    by_status = Counter(r.get("status", "unknown") for r in records)
    high_risk = sum(
        1 for r in records if (r.get("due_diligence") or {}).get("risk") == "high"
    )
    one_week_ago = datetime.now(timezone.utc) - timedelta(days=7)
    this_week = sum(
        1 for r in records
        if _parse_dt(r.get("created_at")) and _parse_dt(r.get("created_at")) >= one_week_ago
    )
    followups = _stale_submitted(records, 7)

    def esc(s):
        return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

    def fmt_date(iso):
        dt = _parse_dt(iso)
        return dt.strftime("%Y.%m.%d") if dt else "—"

    def metric(value, label, extra_class="", delta=""):
        delta_html = f'<div class="delta">{esc(delta)}</div>' if delta else ""
        return (
            f'<div class="metric {extra_class}"><div class="value">{value:02d}</div>'
            f'<div class="label">{esc(label)}</div>{delta_html}</div>'
        )

    metrics_html = (
        metric(total, "总投递数 / ALL APPLICATIONS", "primary", f"+{this_week} THIS WEEK" if this_week else "")
        + metric(by_status.get("pending", 0), "待处理")
        + metric(by_status.get("submitted", 0), "已投递")
        + metric(by_status.get("interview", 0), "面试中")
        + metric(by_status.get("offer", 0), "已获 Offer")
        + metric(by_status.get("rejected", 0), "已拒绝")
        + metric(this_week, "本周新增")
        + metric(high_risk, "高风险公司", "risk")
    )

    notice_html = ""
    if followups:
        notice_html = (
            '<div class="notice"><div><strong>FOLLOW-UP SIGNAL</strong>　'
            f'有 <strong>{len(followups)}</strong> 个岗位超过 7 天没有更新，'
            "建议今天检查是否需要跟进。</div>"
            '<div class="hint">RULE / NO UPDATE ≥ 7 DAYS</div></div>'
        )

    def row_html(r):
        status = r.get("status", "pending")
        status_label = STATUS_LABEL_ZH.get(status, status)
        status_css = {
            "pending": "pending", "submitted": "applied", "interview": "interview",
            "offer": "offer", "rejected": "rejected", "filled": "pending",
        }.get(status, "pending")

        dd = r.get("due_diligence")
        if dd and dd.get("risk") in RISK_COLORS:
            risk = dd["risk"]
            title_attr = f' title="{esc(dd.get("summary",""))}"' if dd.get("summary") else ""
            risk_html = f'<span class="risk {risk}"{title_attr}>{RISK_LABEL_EN[risk]}</span>'
        else:
            risk_html = '<span class="risk none">—</span>'

        report = (dd or {}).get("report")
        report_link = (
            f'<a class="icon-link" href="{esc(report)}" target="_blank" title="背调报告">R</a>'
            if report else ""
        )
        job_link = (
            f'<a class="icon-link" href="{esc(r.get("url",""))}" target="_blank" title="职位链接">↗</a>'
            if r.get("url") else ""
        )

        return f'''<article class="row">
      <div class="cell"><span class="status {status_css}"><span class="dot"></span>{status_label}</span></div>
      <div class="cell"><div class="company">{esc(r["company"])}</div><div class="role">{esc(r["role"])}</div></div>
      <div class="cell channel">{esc(r.get("channel","") or "—")}</div>
      <div class="cell">{risk_html}</div>
      <div class="cell date created">{fmt_date(r.get("created_at"))}</div>
      <div class="cell date">{fmt_date(r.get("updated_at"))}</div>
      <div class="cell links">{job_link}{report_link}</div>
    </article>'''

    ordered = sorted(records, key=lambda r: r.get("updated_at", ""), reverse=True)
    rows_html = "\n".join(row_html(r) for r in ordered)
    body_html = (
        rows_html if records
        else '<p class="empty">还没有记录。用 <code>track_applications.py add</code> 添加第一条投递。</p>'
    )

    year, week, _ = datetime.now().isocalendar()

    html = f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>投递记录看板</title>
<style>
:root{{
  --bg:{BG}; --panel:{PANEL}; --ink:{INK}; --muted:{MUTED};
  --line:{LINE}; --line-strong:{LINE_STRONG};
  --green:{GREEN}; --green-soft:{GREEN_SOFT};
  --red:{RED}; --red-soft:{RED_SOFT};
  --amber:{AMBER}; --amber-soft:{AMBER_SOFT};
  --blue:{BLUE}; --blue-soft:{BLUE_SOFT};
  --mono:{MONO}; --sans:{SANS};
}}
*{{box-sizing:border-box}}
html{{background:var(--bg);color:var(--ink);font-family:var(--sans)}}
body{{margin:0;min-height:100vh;background:var(--bg)}}
a{{color:inherit;text-decoration:none}}
code{{font-family:var(--mono)}}
.shell{{max-width:1440px;margin:0 auto;padding:30px 34px 54px}}
.topbar{{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;border-bottom:1px solid var(--line-strong);padding-bottom:18px}}
.eyebrow{{font:700 11px/1.2 var(--mono);letter-spacing:.14em;color:var(--muted);text-transform:uppercase}}
h1{{font-size:34px;line-height:1.05;letter-spacing:-.035em;margin:9px 0 0;font-weight:700}}
.top-meta{{text-align:right;font:600 12px/1.5 var(--mono);color:var(--muted)}}
.metrics{{display:grid;grid-template-columns:1.4fr repeat(7,minmax(96px,1fr));border-bottom:1px solid var(--line-strong)}}
.metric{{min-height:112px;padding:22px 18px;border-right:1px solid var(--line)}}
.metric:first-child{{padding-left:0}}.metric:last-child{{border-right:0}}
.metric .value{{font:700 31px/1 var(--mono);letter-spacing:-.04em}}
.metric.primary .value{{font-size:48px}}
.metric .label{{font-size:12px;color:var(--muted);margin-top:10px}}
.metric .delta{{font:700 11px/1.3 var(--mono);margin-top:8px;color:var(--green)}}
.metric.risk .value{{color:var(--red)}}
.notice{{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:14px 0;border-bottom:1px solid var(--line);font-size:13px}}
.notice strong{{font-weight:700}}
.notice .hint{{font:600 11px/1.4 var(--mono);color:var(--muted)}}
.list-head{{display:grid;grid-template-columns:110px 1.7fr 1.1fr 100px 100px 130px 92px;padding:14px 0 10px;border-bottom:1px solid var(--line-strong);font:700 10px/1.2 var(--mono);letter-spacing:.09em;color:var(--muted);text-transform:uppercase}}
.row{{display:grid;grid-template-columns:110px 1.7fr 1.1fr 100px 100px 130px 92px;align-items:center;min-height:86px;border-bottom:1px solid var(--line);position:relative;transition:.16s ease}}
.row:hover{{background:#EDEDE8;box-shadow:inset 3px 0 0 var(--ink)}}
.cell{{padding:14px 12px 14px 0;min-width:0}}
.company{{font-weight:720;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
.role{{font-size:12px;color:var(--muted);margin-top:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
.status{{display:inline-flex;align-items:center;gap:7px;font:700 11px/1 var(--mono);white-space:nowrap}}
.dot{{width:7px;height:7px;border:1px solid currentColor;border-radius:50%}}
.status.interview{{color:var(--blue)}}.status.applied{{color:var(--green)}}
.status.pending{{color:var(--muted)}}.status.offer{{color:var(--green)}}.status.rejected{{color:#777}}
.risk{{display:inline-block;padding:5px 7px;border:1px solid currentColor;font:700 10px/1 var(--mono);letter-spacing:.04em}}
.risk.high{{color:var(--red);background:var(--red-soft)}}
.risk.medium{{color:var(--amber);background:var(--amber-soft)}}
.risk.low{{color:var(--green);background:var(--green-soft)}}
.risk.none{{color:var(--muted);background:transparent}}
.channel{{font-size:12px}}
.date{{font:600 11px/1.3 var(--mono);color:var(--muted)}}
.links{{display:flex;justify-content:flex-end;gap:7px}}
.icon-link{{width:30px;height:30px;border:1px solid var(--line-strong);display:grid;place-items:center;font:700 12px/1 var(--mono)}}
.icon-link:hover{{border-color:var(--ink);background:var(--ink);color:#fff}}
.empty{{padding:40px 0;color:var(--muted);font-size:13px}}
.footer{{display:flex;justify-content:space-between;gap:20px;padding-top:18px;font:600 10px/1.5 var(--mono);color:var(--muted)}}
@media (max-width:1100px){{
  .metrics{{grid-template-columns:repeat(4,1fr)}}
  .metric:first-child{{padding-left:18px}}
  .metric{{border-bottom:1px solid var(--line)}}
  .list-head{{display:none}}
  .row{{grid-template-columns:100px 1.5fr 1fr 90px 90px 92px}}
  .row .created{{display:none}}
}}
@media (max-width:760px){{
  .shell{{padding:22px 16px 40px}}
  .topbar{{flex-direction:column}}
  .top-meta{{text-align:left}}
  .metrics{{grid-template-columns:repeat(2,1fr)}}
  .metric.primary .value{{font-size:40px}}
  .notice{{align-items:flex-start;flex-direction:column}}
  .row{{display:grid;grid-template-columns:1fr 84px;gap:0;padding:12px 0}}
  .row .cell{{padding:5px 10px 5px 0}}
  .row .cell:nth-child(1){{grid-column:1/2}}
  .row .cell:nth-child(2){{grid-column:1/2}}
  .row .cell:nth-child(3){{grid-column:1/2}}
  .row .cell:nth-child(4),.row .cell:nth-child(5),.row .cell:nth-child(6){{display:none}}
  .row .links{{grid-column:2/3;grid-row:1/4;align-self:center}}
  .footer{{flex-direction:column}}
}}
</style>
</head>
<body>
<main class="shell">
  <header class="topbar">
    <div>
      <div class="eyebrow">Job Application Assistant / Personal Job Ops</div>
      <h1>投递记录看板</h1>
    </div>
    <div class="top-meta">
      {year} / WEEK {week:02d}<br>生成时间 {datetime.now().strftime('%m.%d · %H:%M')}
    </div>
  </header>

  <section class="metrics" aria-label="投递概览">
    {metrics_html}
  </section>

  {notice_html}

  <section>
    <div class="list-head">
      <div>STATUS</div><div>COMPANY / ROLE</div><div>CHANNEL</div><div>RISK</div><div>CREATED</div><div>UPDATED</div><div style="text-align:right">LINKS</div>
    </div>
    {body_html}
  </section>

  <footer class="footer">
    <span>PERSONAL USE ONLY · APPLICATION LEDGER</span>
    <span>{total} RECORDS · 数据仅保存在本地，不上传任何服务器</span>
  </footer>
</main>
</body>
</html>"""

    with open(args.out, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Dashboard written to {args.out} — open it in a browser.")

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--db", default=DB_PATH_DEFAULT, help="Path to JSON store")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_add = sub.add_parser("add")
    p_add.add_argument("--company", required=True)
    p_add.add_argument("--role", required=True)
    p_add.add_argument("--channel", default="", help="official_site | aggregator")
    p_add.add_argument("--ats", default="")
    p_add.add_argument("--url", default="")
    p_add.add_argument("--notes", default="")
    p_add.add_argument(
        "--status", default="pending", help="pending|filled|submitted|interview|offer|rejected"
    )
    p_add.set_defaults(func=cmd_add)

    p_check = sub.add_parser("check", help="Check if a company already has a record before applying")
    p_check.add_argument("--company", required=True)
    p_check.set_defaults(func=cmd_check)

    p_diligence = sub.add_parser(
        "diligence", help="Attach a due-diligence risk summary + report link to a record"
    )
    p_diligence.add_argument("--company", required=True)
    p_diligence.add_argument("--role", required=True)
    p_diligence.add_argument(
        "--risk", required=True, choices=["low", "medium", "high"], help="Overall risk level"
    )
    p_diligence.add_argument(
        "--report", default="", help="Path to the report file from due_diligence_report.py "
        "(relative to the dashboard's output folder, so the link works when opened)"
    )
    p_diligence.add_argument("--summary", default="", help="One-line summary shown as a tooltip")
    p_diligence.set_defaults(func=cmd_diligence)

    p_list = sub.add_parser("list")
    p_list.add_argument("--status", default="")
    p_list.set_defaults(func=cmd_list)

    p_stats = sub.add_parser("stats", help="Summary counts by status/channel/this week")
    p_stats.set_defaults(func=cmd_stats)

    p_followups = sub.add_parser("followups", help="Submitted applications with no update in N days")
    p_followups.add_argument("--days", type=int, default=10)
    p_followups.set_defaults(func=cmd_followups)

    p_dashboard = sub.add_parser("dashboard", help="Generate a self-contained HTML dashboard")
    p_dashboard.add_argument("--out", default="dashboard.html")
    p_dashboard.set_defaults(func=cmd_dashboard)

    p_export = sub.add_parser("export")
    p_export.add_argument("--out", default="applications.csv")
    p_export.set_defaults(func=cmd_export)

    args = parser.parse_args()
    args.func(args)

if __name__ == "__main__":
    main()
```

## File: references/ats_platforms.md
size: 3493
sha: a3bc5c1b888b3f33be30c654cbf9b990f2ef26ab
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/references/ats_platforms.md

```text
# Common ATS Platforms — Fingerprints & Field Notes

Use this to identify which system is behind a company's application form
before trying to automate it. Fingerprints are based on URL patterns and
common DOM markers; always verify against the live page since companies
customize heavily.

## Greenhouse
- URL pattern: `boards.greenhouse.io/<company-slug>` or embedded widget on
  the company's own domain (`<company>.com/careers` loading a Greenhouse iframe).
- Public API: `https://boards-api.greenhouse.io/v1/boards/<token>/jobs` returns
  open jobs as JSON — prefer this over scraping HTML when available.
- Typical fields: first_name, last_name, email, phone, resume (file), cover
  letter (file, often optional), LinkedIn URL, custom questions (EEO,
  work authorization) defined per-company.

## Lever
- URL pattern: `jobs.lever.co/<company-slug>/<posting-id>`
- Typical fields: name, email, phone, resume (file), LinkedIn/portfolio URLs,
  a few custom questions. Application form is usually a single page.

## Workday
- URL pattern: `<company>.wd1.myworkdayjobs.com` / `wd5` / etc (the number
  varies by Workday data center/tenant).
- Multi-step wizard (My Information → My Experience → Application Questions →
  Voluntary Disclosures → Review). Often requires account creation first.
- Heaviest to automate reliably — selectors are tenant-specific and the UI is
  React-driven with dynamic `data-automation-id` attributes. Budget extra
  time to record real selectors via a browser tool's inspector before
  attempting unattended fills.

## SmartRecruiters
- URL pattern: `jobs.smartrecruiters.com/<company>/<posting-id>`
- Typical fields: name, email, phone, resume upload, sometimes a short
  screening questionnaire.

## iCIMS
- URL pattern: `<company>.icims.com` or `careers-<company>.icims.com`
- Older, more varied markup; often multi-step with account creation.

## BambooHR (careers pages)
- URL pattern: `<company>.bamboohr.com/jobs/`
- Usually simple single-page forms: name, email, phone, resume upload.

## Workable
- URL pattern: `apply.workable.com/<company>/j/<posting-id>`
- Single-page form, generally straightforward to automate.

## 国内常见渠道
- **智联招聘 / 前程无忧(51job) / 猎聘**：聚合平台，非公司官网；投递走平台内
  简历投递流程，通常需要平台账号登录。适合作为 Step 1 的候选来源，但按
  第 2 步的逻辑应优先寻找公司官网/自建招聘系统作为更精准的投递渠道。
- **BOSS直聘**：以"聊天"为主要投递方式（与招聘人员在线沟通后发送简历），
  不是传统表单，不适合脚本化自动填表；建议引导用户手动完成对话式投递，
  或仅用它来发现在招岗位/联系人信息。
- **企业自建招聘系统**（如大厂自有 `careers.<company>.com`）：字段和流程
  因公司而异，需逐一查看后为其单独写 selector 映射，可仿照本文件的结构
  为常用目标公司积累一份 `references/company_specific/<company>.md`。

## General approach for an unrecognized ATS
1. Open the form and inspect field `name`/`id`/`data-*` attributes.
2. Identify: name field(s), email, phone, resume upload `input[type=file]`,
   cover letter upload (if separate), and the submit control.
3. Add a new entry to `ATS_FIELD_MAP` in `scripts/ats_form_filler.py`.
4. Test the fill (not the submit) first, and always let the human review the
   screenshot before authorizing `--confirm-submit`.
```

## File: references/company_due_diligence.md
size: 4841
sha: ee5abca24b7776fe9e8f313f24c3d181f5c5772e
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/references/company_due_diligence.md

```text
# Company Due Diligence (背调) — Sources, Query Templates & Interpretation

Purpose: before (or right after) finding a company hiring for the target
role, pull together publicly available signal on the company's financial
health, legal risk, and employee sentiment — so the user can decide whether
it's worth applying/continuing, not just chase any open posting.

## How to run this step
This relies on `web_search` (or an equivalent search tool) in the calling
agent's session, run live against each source below — NOT a local scraper.
Most of these sites are JS-heavy, aggressively anti-bot, or login-walled, so
scraping them from a script is unreliable and easy to get blocked on. Search
queries against them (via a general search engine) surface the same public
content far more robustly.

For each candidate company, run a small batch of queries (don't skip
categories — a company can look fine on one channel and be a red flag on
another):

### 1. 工商 / 法律风险 (authoritative — check these first)
- `<公司全称> 企查查`
- `<公司全称> 天眼查 被执行人`
- `<公司全称> 司法风险 失信被执行人`
- `<公司全称> 劳动争议 裁判文书`
- `<公司全称> 股权冻结`

Prefer citing the **primary public registries** over secondary aggregators
when a specific claim matters:
- 国家企业信用信息公示系统 (gsxt.gov.cn) — official registration status,
  administrative penalties
- 中国裁判文书网 (wenshu.court.gov.cn) — actual court judgments, including
  labor disputes (劳动争议) filed against the company
- 中国执行信息公开网 (shixin.court.gov.cn) — 失信被执行人 (defaulting on
  court judgments) records
企查查/天眼查 mostly re-package the same registry + judgment data with a
nicer UI — fine as a starting point, but if a specific lawsuit or default
matters to the user's decision, try to confirm against the primary source.

### 2. 员工口碑 / 工作体验
- `<公司全称> 知乎 靠谱吗`
- `<公司全称> 知乎 员工 评价`
- `<公司全称> 看准网` or `<公司全称> Kanzhun review`（看准网/BOSS直聘企业版）
- `<公司全称> 脉脉`
- `<公司全称> 小红书 入职 感受`
- `<公司全称> 小红书 吐槽`

### 3. 综合口碑 / 品牌
- `<公司全称> 抖音 员工日常`（多为官方账号/营销内容，权重放低，主要看评论区真实反馈）
- `<公司全称> 加班 猝死 舆情`（仅在有具体线索时补充搜索，不要预设结论）
- `<公司全称> 融资历史`（用于判断财务健康度/现金流风险，尤其是早期创业公司）

## How to interpret and present findings

- **Cite sources.** Every claim in the report should be attributable to a
  specific source (知乎回答/企查查记录/裁判文书号/小红书帖子), not stated as
  bare fact. Follow the same copyright-safe paraphrasing approach used
  elsewhere — summarize in your own words, don't reproduce long quotes.
- **Weight primary/official records above social commentary.** A 裁判文书网
  labor-dispute judgment is a fact; a single 知乎 complaint is one person's
  account and may be biased, outdated, or exaggerated — note that distinction
  explicitly in the report rather than presenting both with equal confidence.
- **Watch for astroturfing.** 抖音/小红书 company-branded content and posts
  that read like recruiting marketing aren't independent employee sentiment
  — flag this rather than counting it toward "positive reviews."
- **Small sample ≠ trend.** One or two negative reviews out of a large
  company is normal noise; a consistent pattern across multiple independent
  sources (esp. combined with an actual court record) is the real signal.
- **This is not legal or financial advice.** Present findings as information
  to weigh, not a verdict — the user makes the final call on whether to
  apply/accept an offer.

## Red-flag checklist (surface these prominently if found)
- [ ] 失信被执行人 / 被强制执行 records
- [ ] Multiple 劳动争议 (labor dispute) judgments, especially repeated ones
      over wages/overtime/unpaid social insurance
- [ ] Frequent legal-entity or equity changes in a short period (可能预示
      资金链或控制权问题)
- [ ] Recurring, specific employee complaints about unpaid wages, excessive
      unpaid overtime (996/007), or forced resignation practices — especially
      when corroborated across more than one independent source/platform
- [ ] Recent large-scale layoffs or funding collapse reported in press/社媒

## Output format
Feed structured findings into `scripts/due_diligence_report.py` to produce
a shareable Markdown/HTML report per company (see that script's `--help`).
Keep each section short — a due-diligence report is a decision aid, not an
exhaustive dossier.
```

## File: references/similar_projects.md
size: 3547
sha: a50fd640e3cbdfbbd498fb0d8c795e195fe1b533
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/references/similar_projects.md

```text
# Similar Open-Source Projects — What We Borrowed

A quick survey of existing GitHub projects in this space, and which ideas
made it into this skill (in our own words/implementation — no code copied).

## Auto_job_applier_linkedIn (GodsScion, ~2.8k stars)
https://github.com/GodsScion/Auto_job_applier_linkedIn

- **Pause-before-submit as a first-class setting** — confirms our own
  "never auto-submit without confirmation" rule is a common, expected
  pattern in this space, not an unusual restriction.
- **`safe_mode` / `click_interval`** — randomized delay between actions to
  avoid looking like a bot and to avoid overwhelming a site. → adopted as
  the "batch in small groups (5–10) with review checkpoints" rule in
  SKILL.md; `ats_form_filler.py` should add explicit delays if you extend
  it to handle multiple applications in one run.
- **Skip already-applied / blacklisted companies** — before filling a new
  application, check whether you've already got a record for that company.
  → adopted as the new `track_applications.py check --company` subcommand;
  wire it into Step 4 of the workflow before opening a new form.
- **Local-only data, no cloud upload** — matches our tracker's design
  (plain JSON on disk, CSV/HTML export, nothing sent anywhere).
- **A dedicated "Applied Jobs history" view in a local control panel** →
  adopted as `track_applications.py dashboard`, which generates a
  self-contained HTML page (summary cards + status bar chart + full table)
  instead of a running Flask app, to keep this skill dependency-light.

## simonfong6/auto-apply
https://github.com/simonfong6/auto-apply

- Confirms Greenhouse/Lever/Workday/Jobvite as the right set of major ATS
  platforms to target first — matches `references/ats_platforms.md`.

## Pickle-Pixel/ApplyPilot
https://github.com/Pickle-Pixel/ApplyPilot

- **Explicit "stages 1–5 only" mode**: discover → score-against-resume →
  tailor resume → write cover letter → fill form, with submission left as
  a manual last step. This is essentially the mode we default to; treat
  full autonomous submission as something only offered when the user
  explicitly asks for a batch to go all the way through, and even then
  always with the review checkpoint from Step 4 of SKILL.md.
- **"Never fabricates" experience when tailoring a resume** — same
  constraint we already state under "Non-negotiable ground rules".

## Commercial "Job Application Tracker" spreadsheet templates (Gumroad/Etsy)
Many independent listings converge on the same shape, which is a useful
signal for what a tracker needs regardless of implementation:

- Dashboard summary (totals, by status, by channel/source, by week)
- Duplicate detection when logging a job you may have already tracked
- Follow-up reminders based on days-since-last-update
- A separate notes/company-research field

All four are now in `track_applications.py` (`stats`, `add`'s duplicate
warning, `followups`, and the `--notes` field respectively).

## What we deliberately did NOT borrow
- Fully unattended multi-hundred-application "spray and pray" runs (some
  tools advertise "apply to 100+ jobs in under an hour"). This conflicts
  with our accuracy/quality and anti-spam principles — see SKILL.md's
  ground rules. Low-quality, unreviewed applications also just perform
  worse for the user.
- CAPTCHA-solving services/bypass techniques that some auto-apply tools
  integrate. We stop and hand control back to a human instead — see the
  CAPTCHA handling in `ats_form_filler.py`.
```

## File: .gitignore
size: 345
sha: 553ab89df87a9818c4f1a8e61ebe432e3c8c3516
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/.gitignore

```text
# Personal data generated by using this tool — never commit your own
# job-search records.
applications.json
applications.csv
dashboard.html
*_report.html
*_report.md
*_findings.json

# Python
__pycache__/
*.pyc
*.pyo
.venv/
venv/

# Playwright artifacts (screenshots taken while filling forms)
filled_form.png

# OS noise
.DS_Store
Thumbs.db
```

## File: company_due_diligence.md
size: 6470
sha: a534d4b659b5c856db76c6b96f49365ae028a440
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/company_due_diligence.md

```text
# Company Due Diligence (背调) — Sources, Query Templates & Interpretation

Purpose: before (or right after) finding a company hiring for the target
role, pull together publicly available signal on the company's financial
health, legal risk, and employee sentiment — so the user can decide whether
it's worth applying/continuing, not just chase any open posting.

## How to run this step
This relies on `web_search` (or an equivalent search tool) in the calling
agent's session, run live against each source below — NOT a local scraper.
Most of these sites are JS-heavy, aggressively anti-bot, or login-walled, so
scraping them from a script is unreliable and easy to get blocked on. Search
queries against them (via a general search engine) surface the same public
content far more robustly.

For each candidate company, run a small batch of queries (don't skip
categories — a company can look fine on one channel and be a red flag on
another):

### 1. 工商 / 法律风险 (authoritative — check these first)
- `<公司全称> 企查查`
- `<公司全称> 天眼查 被执行人`
- `<公司全称> 司法风险 失信被执行人`
- `<公司全称> 劳动争议 裁判文书`
- `<公司全称> 股权冻结`

Prefer citing the **primary public registries** over secondary aggregators
when a specific claim matters:
- 国家企业信用信息公示系统 (gsxt.gov.cn) — official registration status,
  administrative penalties
- 中国裁判文书网 (wenshu.court.gov.cn) — actual court judgments, including
  labor disputes (劳动争议) filed against the company
- 中国执行信息公开网 (shixin.court.gov.cn) — 失信被执行人 (defaulting on
  court judgments) records
企查查/天眼查 mostly re-package the same registry + judgment data with a
nicer UI — fine as a starting point, but if a specific lawsuit or default
matters to the user's decision, try to confirm against the primary source.

### 2. 员工口碑 / 工作体验
- `<公司全称> 知乎 靠谱吗`
- `<公司全称> 知乎 员工 评价`
- `<公司全称> 看准网` or `<公司全称> Kanzhun review`（看准网/BOSS直聘企业版）
- `<公司全称> 脉脉`
- `<公司全称> 小红书 入职 感受`
- `<公司全称> 小红书 吐槽`

### 3. 综合口碑 / 品牌
- `<公司全称> 抖音 员工日常`（多为官方账号/营销内容，权重放低，主要看评论区真实反馈）
- `<公司全称> 加班 猝死 舆情`（仅在有具体线索时补充搜索，不要预设结论）
- `<公司全称> 融资历史`（用于判断财务健康度/现金流风险，尤其是早期创业公司）

## How to interpret and present findings

- **Cite sources.** Every claim in the report should be attributable to a
  specific source (知乎回答/企查查记录/裁判文书号/小红书帖子), not stated as
  bare fact. Follow the same copyright-safe paraphrasing approach used
  elsewhere — summarize in your own words, don't reproduce long quotes.
- **Weight primary/official records above social commentary.** A 裁判文书网
  labor-dispute judgment is a fact; a single 知乎 complaint is one person's
  account and may be biased, outdated, or exaggerated — note that distinction
  explicitly in the report rather than presenting both with equal confidence.
- **Watch for astroturfing.** 抖音/小红书 company-branded content and posts
  that read like recruiting marketing aren't independent employee sentiment
  — flag this rather than counting it toward "positive reviews."
- **Small sample ≠ trend.** One or two negative reviews out of a large
  company is normal noise; a consistent pattern across multiple independent
  sources (esp. combined with an actual court record) is the real signal.
- **This is not legal or financial advice.** Present findings as information
  to weigh, not a verdict — the user makes the final call on whether to
  apply/accept an offer.

## Red-flag checklist (surface these prominently if found)
- [ ] 失信被执行人 / 被强制执行 records
- [ ] Multiple 劳动争议 (labor dispute) judgments, especially repeated ones
      over wages/overtime/unpaid social insurance
- [ ] Frequent legal-entity or equity changes in a short period (可能预示
      资金链或控制权问题)
- [ ] Recurring, specific employee complaints about unpaid wages, excessive
      unpaid overtime (996/007), or forced resignation practices — especially
      when corroborated across more than one independent source/platform
- [ ] Recent large-scale layoffs or funding collapse reported in press/社媒

## Known limitation: 小红书/抖音 coverage is incomplete by design

This workflow uses a general search engine (`web_search`), never a logged-in
scraper — see "How to run this step" above for why. The tradeoff: **general
search engines index 小红书/抖音 content very poorly**, so a company can have
real posts/comments on those platforms that a `web_search` pass simply won't
surface, even with well-formed queries.

- 小红书 in particular gates most content behind login, and even public posts
  are inconsistently crawled by external search engines — a note the user
  found by searching directly inside the 小红书 app may not turn up here.
- 抖音 comments (where real sentiment usually lives, as opposed to the
  official account's video captions) are almost never indexed at all.

**Do not treat an empty result from these two sources as "no findings" —
treat it as "not covered by this method."** If the user has already found
relevant posts themselves (by searching inside the app), the right move is
to have them share the content or link directly, then fold it into the
report's 社交媒体口碑 section attributed as **user-provided**, not
Claude-sourced — same sourcing discipline as everything else in this file.

Logging in as the user to search 小红书/抖音 directly is a possible
technical fix but is deliberately out of scope here: it risks the user's
account (aggressive anti-automation risk-control, possible bans) and would
require building and maintaining login/cookie persistence and anti-scraping
workarounds — a different, riskier kind of tool than the rest of this skill.

## Output format
Feed structured findings into `scripts/due_diligence_report.py` to produce
a shareable Markdown/HTML report per company (see that script's `--help`).
Keep each section short — a due-diligence report is a decision aid, not an
exhaustive dossier.
```

## File: docs/company-report-screenshot.png
size: 228988
sha: 95aa0e5bfe5ca8f84f0cad65288ebe7e0fe34dbc
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/company-report-screenshot.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/company-report-screenshot.png

## File: docs/dashboard-screenshot.png
size: 96378
sha: 17e8040a494aa9ffd0d3a29a6995f85faddf0bf6
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/dashboard-screenshot.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/dashboard-screenshot.png

## File: docs/readme-hero.png
size: 2332245
sha: b78d02a09fc2beb4f9cacca0d4e3fb4967ac65b4
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/readme-hero.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/docs/readme-hero.png

## File: job-application-assistant.skill
size: 348795
sha: a1c3e6bf851c11bc429b940a26010e8f672f9671
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/job-application-assistant.skill

Content is not inlined in the catalog. Read the upstream file: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/job-application-assistant.skill

## File: LICENSE
size: 1065
sha: a41878bf098277b74c2389226d1cba6c5fd70942
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 LH-kevin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: README.en.md
size: 6710
sha: 8d0519d731117c3cd47c8b663c95fde7e35fbe4e
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/README.en.md

````text
# job-application-assistant

**A personal job-search AI Skill for Claude / Codex**

*[中文](README.md)*

<p align="center">
  <img src="docs/readme-hero.png" alt="job-application-assistant — a personal AI Skill for job hunting" width="100%">
</p>

> **In one sentence:** let AI help you **find target companies → vet them before applying → carefully assist with application forms → track every application**, while every real submission still requires your confirmation.

This is a **personal job-search** Skill for Claude / Codex, not a recruiting SaaS product.  
There is no server, no account system, and no cloud sync. Your application data stays in a local JSON file on your machine.

---

## Understand it in 30 seconds

### 1. Install the Skill in Claude / Codex

- **Claude (desktop / web):** go to `Settings → Capabilities → Skills`, then upload this project folder or a packaged `.skill` file.
- **Claude Code / Codex:** place this project in the skills directory used by that tool.

### 2. Tell it what kind of role you want

For example:

```text
Help me find companies hiring for AI Agent development roles.
Prefer each company's official careers page.
Before I apply, run company due diligence.
After I confirm, help me fill the application form
and add the application to my tracker.
```

### 3. The Skill moves the process forward

```text
Find openings
    ↓
Choose target companies
    ↓
Run company due diligence
    ↓
Decide whether to continue
    ↓
Assist with the application form
    ↓
You confirm the real submission
    ↓
Track the application + follow up
```

**Less repetitive copying, less manual research, and less scattered tracking.**

---

## What it helps you do

|  | Capability | What you get |
|---|---|---|
| 🔎 | **Find openings** | Search for companies hiring for a target role and prefer each company's **official careers page** |
| 🏢 | **Vet before you apply** | Collect public signals on financial health, legal/judicial risk, employee sentiment, and social-media commentary |
| 📝 | **Assist with ATS forms** | Help fill common ATS forms in a visible browser, including Greenhouse, Lever, and Workday |
| 📊 | **Track applications** | Keep company, role, channel, status, risk label, and follow-up information in one place |
| 🔁 | **Detect duplicates** | Check whether you have already applied to the same company |
| 🔒 | **Keep data local** | No account, no server, no cloud sync; your application records stay on your machine |

---

## What the output looks like

### Application ledger

See every application, current status, channel, last update, and due-diligence risk label at a glance.

<p align="center">
  <img src="docs/dashboard-screenshot.png" alt="Application dashboard" width="100%">
</p>

### Company due-diligence report

Before deciding whether to keep applying or interviewing, consolidate legal/judicial risk, employee sentiment, and public social-media commentary into one report.

<p align="center">
  <img src="docs/company-report-screenshot.png" alt="Company due-diligence report" width="78%">
</p>

Both pages are self-contained static HTML. No server is required, and the pages are regenerated from your own local data.

---

## Why this is not a one-click auto-apply tool

The project deliberately keeps **human confirmation** in the loop.

- **No automatic submission:** every real batch requires explicit confirmation.
- **No CAPTCHA bypass:** the workflow stops and hands control back to you.
- **No fabricated resume experience:** it does not invent facts to make you look more qualified.
- **No fabricated due-diligence findings:** findings must be sourced.
- **No unattended high-volume applying:** the workflow uses review checkpoints instead.

The goal is not to maximize application volume. The goal is to make your job search **more informed, controllable, and easier to follow through**.

---

## Install

The project is packaged as a **Claude Skill**:

```text
SKILL.md
scripts/
references/
```

### Claude

1. Open Claude.
2. Go to `Settings → Capabilities → Skills`.
3. Upload this project folder or a packaged `.skill` file.

### Claude Code / Codex

Place the project into the skills directory documented by the tool you use.

---

## Python dependencies

The tracking and report-generation scripts:

- `scripts/track_applications.py`
- `scripts/due_diligence_report.py`

use only the Python standard library.

The search and ATS form-assistance scripts require:

```bash
pip install -r requirements.txt
playwright install chromium
```

Chromium is only needed if you use `ats_form_filler.py`.

---

## Quick CLI demo

```bash
# Track an application
python scripts/track_applications.py add \
  --company "Acme Corp" --role "Frontend Engineer" \
  --channel official_site --url "https://acme.com/careers/123" \
  --status submitted

# Check whether you already applied
python scripts/track_applications.py check --company "Acme Corp"

# See applications that need follow-up
python scripts/track_applications.py followups --days 7

# Attach a due-diligence report
python scripts/due_diligence_report.py --input acme_findings.json \
  --out acme_report.html --format html

python scripts/track_applications.py diligence \
  --company "Acme Corp" --role "Frontend Engineer" \
  --risk medium --report acme_report.html --summary "1 labor dispute judgment"

# Generate the dashboard
python scripts/track_applications.py dashboard --out dashboard.html
```

See each script's `--help` output and docstring for the full command reference.

---

## Workflow and design notes

See [`SKILL.md`](SKILL.md) for the full step-by-step workflow.

See [`references/`](references/) for the design notes behind each module, including which open-source auto-apply patterns were studied and which ones were deliberately not adopted.

---

## Data and privacy

This is a **local-first personal job-search tool**:

- no server
- no account system
- no cloud sync
- application data stored in a local JSON file
- real submissions require human confirmation

---

## Disclaimer

This is a personal productivity tool, not legal, financial, or career advice.

Due-diligence reports aggregate public information and social-media commentary. Verify any information that materially affects your decision—such as a specific lawsuit or company registration status—against a primary or authoritative source before acting.

You are responsible for complying with the terms of service of any site this tool interacts with.

---

## License

MIT — see [LICENSE](LICENSE).

---

If this project improves your job-search workflow, consider giving it a **Star**, opening an **Issue**, or sharing your feedback.
````

## File: requirements.txt
size: 298
sha: 6a7d507f8edfe7c4347b38189e5179f500ac0a69
upstream: https://github.com/lh-kevin/job-application-assistant/blob/HEAD/requirements.txt

```text
# Core (used by search_target_companies.py / find_career_page.py)
requests>=2.31
beautifulsoup4>=4.12

# Optional — only needed if you use scripts/ats_form_filler.py to fill
# application forms with browser automation. After installing, also run:
#   playwright install chromium
playwright>=1.40
```
