From ce96cfb72ca9b13351f31c2473206f29a9e3e087 Mon Sep 17 00:00:00 2001 From: ender Date: Wed, 11 Nov 2026 13:32:32 +0800 Subject: [PATCH] feat(resume): write a Master resume that covers every Fact Add `master plan` and `master save`, which write one complete Chinese and English resume per Candidate: master-resume.zh.md and master-resume.en.md. It writes out every active, sourced Fact in full, or lists it as left out with a reason, so the user can review a Candidate's Facts in one place and later extracts start from the same wording. It is internal, with no PDF. - Sections in a fixed order: summary, grouped skills, highlights, experience blocks (context, scope, grouped long-form achievements, tech), projects, education, certificates and training, awards and publications, languages, then Gaps and Left out appendices. - Experience blocks may be a self-directed stretch (`name`) or one project with titles at several companies (`roles`). - Any item may carry a `gap`, shown in place and collected in the Gaps appendix with the Facts' missing fields. - `master save` refuses unusable Facts, numbers not in the cited Facts, Glossary mismatches, Chinese in English, uncovered Facts, and highlights that no experience or projects line backs. - `candidate show` and `master plan` report a stale Master resume: a covered Fact changed or was removed, a usable Fact is not covered, or the Strategy's guidance changed. `validate` checks it after hand edits. - Tailored resumes and the Master resume share ResumeWriter; Tailored resume output, refusals and `resume plan` are unchanged. Existing Data folders need no migration: the files are new and written on request, and validate accepts Candidate folders without them. Fixes #24 Co-Authored-By: Claude Opus 5.5 --- CONTEXT.md | 7 + README.md | 1 + README.zh-TW.md | 1 + skills/headhunter/SKILL.md | 75 +++- skills/headhunter/scripts/hh.py | 631 +++++++++++++++++++++++++++----- 5 files changed, 622 insertions(+), 93 deletions(-) diff --git a/CONTEXT.md b/CONTEXT.md index ca6bafc..cf2848a 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -120,6 +120,13 @@ High, medium, or low, with reasons, from the Fit score and the Hard requirements. A rule-based estimate, never a probability. _Avoid_: success probability, chance, odds +**Master resume**: +The Candidate's complete resume, one in Chinese and one in English: every +active, sourced Fact written out in full and grouped as a resume, or listed as +left out with a reason, with the gaps still to fill marked in place. It is +internal and never sent; extracts for specific contexts start from it. +_Avoid_: base resume, full CV, career document + **Tailored resume**: The pair of resumes written for one Application, one in Chinese and one in English, starting from the Role profile of the Application's Role and using only diff --git a/README.md b/README.md index 8dc00ac..4aa98b7 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ A job search piles up more than anyone can keep straight: old resumes, notes, wo - **Role profiles** — One candidate can pursue several roles at once, such as backend engineer and tech lead. For each role it lists the requirements, links the facts that support each one with a reason, and names the gaps: no evidence, only unconfirmed inferences, or only self-reported evidence, each with a way to close it. When facts change, it tells you which profiles are out of date. Search candidates by role, by required skill, or by roles with no must-have gaps. - **Job reading** — Give it jobs in any form: a listing or job link from 104, CakeResume, Yourator, a company careers page or LinkedIn, a PDF or HTML file, a screenshot, or copied text, one job or many. It reads the listing, screens the titles, then reads each job in full and saves a snapshot: must-haves, nice-to-haves, duties, salary and location, with requirements tagged from the same taxonomy as candidate facts. Yourator and careers pages are read directly, following each site's robots.txt. 104 and CakeResume block automated requests, so the skill guides you instead: scroll the search results until every job has loaded, copy the page and paste it, and job pages are read in your browser or from text you copy. LinkedIn is read only from your signed-in browser or pasted text. - **Job evaluation** — For one candidate, or across your whole database: it finds the candidates whose roles fit a job and evaluates each against the role that fits, or against all of the candidate's facts when none does, then offers to create a role from the job. Each evaluation gives a fit score from a fixed rubric (skill overlap, seniority, industry and domain, achievements, salary, location and work mode), reasons tied to specific facts and job requirements, gaps and risks with how to close them, and a high / medium / low success rating with its reasons. Failing a hard requirement, such as minimum years or a required degree, lowers the rating by one level. Requirements that keep appearing in the jobs evaluated under a role are proposed as changes to that role, applied only when you accept them. +- **Master resume** — One complete Chinese and English resume per candidate, kept for your own review rather than sent. It writes out every fact with a source in full: a summary, grouped skills and highlights, then each job with what the organization is, the candidate's scope, achievements grouped by project with the problem, the decision, the action and the measured result, and the tools used, followed by projects, education, certificates and training, awards and publications, and languages. Every fact is either written or listed as left out with a reason, so the file doubles as a readable overview of the candidate's facts. Whatever is missing, such as a result or a team size, is marked in place and collected as a list to ask about, and you are told when new or changed facts, or a changed strategy, leave it out of date. - **Tailored resumes** — A Chinese and an English resume for each evaluated application, in Markdown and PDF. Each starts from the profile of the role the job was evaluated under, follows the resume decisions recorded in the candidate's strategy, such as which title to use or which experience to leave out, puts the most relevant facts first, and uses only facts with a source: every line names the facts it comes from, numbers must match them, skills the candidate lacks stay out, and companies, titles and schools always get the same English names from the candidate's glossary. The PDFs are printed with Chrome, Chromium or Edge, and their text copies cleanly into applicant tracking systems. - **Application tracking** — Every candidate × job pair moves through stages (found → evaluated → preparing → applied → interview rounds → offer → closed), with a dated timeline, each interview round recorded separately, and a next step with a due date while it is open. It lists overdue follow-ups across all candidates, shows progress by candidate, role, job and company, and records how each closed application ended: hired, declined, rejected or withdrawn. - **Feedback loop** — Log feedback from HR, interviewers, the candidate and yourself, with a cause and a concrete fix, and track each fix until it is done; a fix that produces new material, such as a portfolio piece, ends with importing it as a source. Causes that recur across a candidate's applications or under one role turn into proposed changes to the strategy, role profiles and resumes, applied only when you agree. What feedback says about a company builds up into company notes across candidates. Closed applications are compared with their success ratings to show where the scoring over- or under-estimates, and any rubric change stays your decision. diff --git a/README.zh-TW.md b/README.zh-TW.md index 2f5a55b..39e1836 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -16,6 +16,7 @@ - **角色檔案**:一位候選人可以同時鎖定好幾個角色,例如後端工程師和技術主管。每個角色會列出條件,把支持每條條件的事實連結起來並說明理由,同時指出缺口:沒有證據、只有未確認的推論,或只有自述的證據,每個缺口都附上補強方式。事實有變動時,會告訴你哪些角色檔案需要更新。可以依角色、要求的技能,或必備條件沒有缺口的角色來查詢候選人。 - **讀取職缺**:職缺可以用任何形式交給它:104、CakeResume、Yourator、企業官網或 LinkedIn 的列表或職缺網址、PDF 或 HTML 檔、截圖,或複製的文字,一個或一批都可以。它會先讀標題粗篩,再逐一讀取完整職缺內容並存成快照:必備條件、加分條件、工作內容、薪資與地點,條件會用和候選人事實相同的標籤分類。Yourator 和企業官網直接讀取,並遵守各網站的 robots.txt。104 和 CakeResume 會擋自動化請求,所以改由 skill 引導你:把搜尋結果捲到所有職缺都載入、複製整頁貼上,職缺頁則從你的瀏覽器讀取或用你複製的文字。LinkedIn 只讀你已登入瀏覽器中開啟的頁面或你貼上的文字。 - **職缺評估**:可針對一位候選人,或從整個資料庫找出角色符合職缺的候選人,並依符合的角色評估;沒有符合的角色時,改用候選人的全部事實評估,並提議從這個職缺建立新角色。每份評估依固定評分標準(技能重疊、職級、產業與領域、成就、薪資地點與工作模式)給出適合度分數,推薦原因會對應到具體的事實和職缺條件,列出缺口與風險及補強方式,並給出高/中/低的成功率等級與理由。不符合硬性條件(例如最低年資或指定學歷)時,等級降一級。同一角色下評估過的職缺若反覆出現同樣的條件,會提議加進該角色,經你同意才套用。 +- **完整版履歷**:每位候選人一份中文與英文的完整履歷,留給你自己查閱,不拿去投遞。它把每一條有出處的事實完整寫出:摘要、分組的技能與核心亮點,接著每段經歷寫出這個組織在做什麼、候選人負責的範疇、依專案分組的成就(寫出問題、判斷、做法與附量測條件的結果),以及用到的技術,最後是專案、學歷、證照與訓練、獎項與發表,以及語言。每一條事實不是寫進履歷,就是列為不寫並說明原因,所以這份檔案也是候選人事實的完整總覽。缺少的內容,例如成果或團隊人數,會在原處標示並整理成待追問的清單;有新增或變動的事實、或求職策略改變時,會告訴你它需要更新。 - **客製履歷**:每個評估過的投遞都產出中文與英文兩版,Markdown 與 PDF 格式。履歷從該職缺評估時所用角色的角色檔案出發,遵守候選人求職策略裡記下的履歷寫法決定,例如要用哪個職稱、哪段經歷不放,把最相關的事實放前面,只使用有出處的事實:每一行都註明出自哪些事實,數字必須和事實一致,候選人缺少的技能不會寫進去,公司、職稱和學校的英文名稱一律依照候選人的對照表。PDF 用 Chrome、Chromium 或 Edge 產生,文字可以正確複製,求職系統(ATS)也能正確讀取。 - **投遞進度追蹤**:每組「候選人 × 職缺」依階段推進(發現 → 已評估 → 準備中 → 已投遞 → 面試 → Offer → 結案),保留有日期的歷程,每輪面試分開記錄,進行中的投遞都有下一步與期限。可以列出所有候選人逾期的待辦,依候選人、角色、職缺或公司查看進度,結案時記錄結果:錄取、婉拒、未錄取或撤回。 - **回饋與修正**:記錄來自 HR、面試官、候選人與你自己的回饋、原因分類與具體修正方向,並追蹤每項修正直到完成;會產出新資料的修正(例如作品集)要匯入成資料來源才算完成。同一位候選人的多次投遞或同一角色下重複出現的原因,會變成對求職策略、角色檔案與履歷的修改提議,經你同意才套用。回饋中關於公司的內容會跨候選人累積成公司情報。結案的投遞會和成功率等級比對,指出評分高估或低估之處,要不要調整評分標準由你決定。 diff --git a/skills/headhunter/SKILL.md b/skills/headhunter/SKILL.md index 2566b3e..13f8737 100644 --- a/skills/headhunter/SKILL.md +++ b/skills/headhunter/SKILL.md @@ -1,6 +1,6 @@ --- name: headhunter -description: AI headhunter for the user's own job search or for many candidates at once. Use when the user wants to add, update, search or archive candidates in their candidate database; import any material about a candidate (notes, work logs, photos, resumes, GitHub repos) and have it checked, tagged and followed up with questions; read a job listing URL (104, CakeResume, Yourator, LinkedIn, company careers pages) and evaluate jobs against candidates and their target roles with a fit score and a success rating; write a tailored Chinese and English resume for a job; or track application progress, interview feedback and what to fix next. +description: AI headhunter for the user's own job search or for many candidates at once. Use when the user wants to add, update, search or archive candidates in their candidate database; import any material about a candidate (notes, work logs, photos, resumes, GitHub repos) and have it checked, tagged and followed up with questions; read a job listing URL (104, CakeResume, Yourator, LinkedIn, company careers pages) and evaluate jobs against candidates and their target roles with a fit score and a success rating; write a complete Chinese and English master resume of every fact, or a tailored resume for a job; or track application progress, interview feedback and what to fix next. --- # headhunter @@ -64,6 +64,8 @@ python3 /scripts/hh.py | `resume plan ` | Show what an Application's resumes start from: the Candidate's Strategy, the Role profile, the Evaluation's evidence, what to leave out, the usable Facts and the Glossary | | `resume save [--replace]` | Write `resume.zh.md` and `resume.en.md` from JSON or YAML on stdin and print both to PDF; nothing is written if any check fails | | `resume pdf ` | Check both resumes and print them to PDF again, after editing them by hand | +| `master plan ` | Show what the Master resume is written from: the Candidate's Strategy, every usable Fact by organization and kind with its missing fields, the Glossary and the header, and whether the Master resume is current | +| `master save [--replace]` | Write `master-resume.zh.md` and `master-resume.en.md` from JSON or YAML on stdin; nothing is written if any check fails | | `validate []` | Check `taxonomy.yml`, Candidate folders (with their Roles, Evaluations, resumes, Applications and Feedback) and Job snapshots | | `index` | Delete and rebuild `index.sqlite` | | `search candidates` / `search facts` | Filter the Index (see Search) | @@ -85,6 +87,8 @@ Searches rebuild the Index first when any file changed. Run `validate` after edi imports/ Import reports, including unanswered follow-up questions glossary.yml Chinese ↔ English names for companies, titles, schools, terms strategy.md job-search strategy; its Roles section is kept by the script + master-resume.zh.md Master resume in Chinese: every usable Fact, citing them; never sent, no PDF + master-resume.en.md the same in English roles// role.yml Role: title, level, industries, priority, state, requirements profile.md Role profile: positioning, evidence, gaps @@ -253,6 +257,54 @@ The script adds `candidate`, `job`, `evaluated`, `candidate_level` (from `profil The fit score is the weighted sum, rounded. It maps to a Success rating: 75 and above high, 55 to 74 medium, below 55 low. Failing any hard requirement lowers the rating by one level; low stays low. The reasons name the band, each failed or unconfirmed hard requirement, the must-haves missing or unconfirmed, and the strongest and weakest dimensions. +**master-resume.zh.md / master-resume.en.md**: the Master resume, one per Candidate. A YAML block between `---` lines (`candidate`, `lang`, `written`, and `built_from`: a digest of the Strategy's guidance and of every Fact it covers), then the resume, written by `master save` from what you give it: + +```yaml +headline: {zh: 後端與資料工程師, en: Backend and data engineer, facts: [f-001, f-004]} +summary: # one or more sentences, not tied to a Role + - {zh: ..., en: ..., facts: [f-004, f-001]} +skills: # grouped; where each was used, with years only from Fact periods + - {label: {zh: 程式語言, en: Languages}, zh: Python、SQL(2020 起), en: "Python, SQL (since 2020)", facts: [f-011]} +highlights: # the 3–5 strongest results; their Facts are cited in experience or projects too + - {zh: ..., en: ..., facts: [f-002, f-003]} +experience: # reverse chronological + - org: 智慧水表專案 # a company in glossary.yml, cited by one of its Facts; or name: {zh, en} + title: 資料工程師 # optional: a title in glossary.yml that its Facts state + period: 2020-01..2022-02 # optional: the period of one of its Facts + facts: [f-006, f-004] + roles: # optional: one line per title, such as titles at several companies + - {org: 乙科技, title: 資料工程師, period: 2021-07..2022-02, facts: [f-005]} + context: {zh: ..., en: ..., facts: [f-006]} # what the organization or project is + scope: {gap: {zh: 團隊人數, en: team size}, facts: [f-004]} # team size, ownership, reporting line + groups: # achievements by project or theme, most impactful first + - heading: {zh: 資料匯入, en: Data import} # optional + bullets: [{zh: ..., en: ..., facts: [f-007]}] + tech: {zh: Kafka、PostgreSQL, en: "Kafka, PostgreSQL", facts: [f-008]} +projects: [{zh: ..., en: ..., facts: [f-014]}] +education: [{school: 範例大學, zh: 資訊管理學士, en: B.S. in Information Management, period: 2014-09..2018-06, facts: [f-012]}] +certificates: [{zh: ..., en: ..., facts: [f-015]}] # certificates and training +awards: [] # awards, publications, talks, patents +languages: [{zh: 英文:TOEIC 850(2019), en: "English: TOEIC 850 (2019)", facts: [f-013]}] +left_out: [{facts: [f-010], zh: 依 Strategy 不放這段經歷, en: The Strategy leaves this role out}] +``` + +- `org` is a company in `glossary.yml`; a self-directed stretch, such as independent development or study, takes `name` instead. `school` and `period` are optional in `education`. +- Any item may add `gap: {zh, en}`: what is missing there, such as a result or a team size. The line shows it as `【待補:…】` or `[To fill: …]`. An item with only a gap, and optionally its Facts, stands for a line no Fact can fill yet. +- Sections appear in the order above, after the header the script writes from `profile.yml`; a section with no items is left out. Two appendices follow, not part of the resume: Gaps (待補) lists every gap with its Facts' `missing` fields, and Left out (未寫入) lists `left_out` with its reasons. +- Every line other than headings and gap-only lines ends with the Facts it comes from, as in Tailored resumes. + +`master save` refuses a Master resume when: + +- a Fact is inferred, superseded or in conflict, or an item cites none +- a number in a line is not in the statements or periods of the Facts it cites +- a company, title, school or location is not in `glossary.yml`, an `org` is not the organization of one of its Facts, a title or school is not in its Facts, or a period is not one of its Facts' +- the Chinese and English lines name a Glossary entry differently, or the English has Chinese in it +- an active, sourced Fact is neither cited nor listed under `left_out`, or `left_out` lists a cited or unusable Fact +- a highlight cites a Fact that no `experience` or `projects` line cites +- the headline or summary is missing + +The Master resume is stale when a Fact it covers changed or was removed, an active, sourced Fact is not covered, or the Strategy's guidance changed; `candidate show` and `master plan` say which. `validate` checks the Markdown after hand edits as it checks Tailored resumes; lines that hold only a gap need no Facts, and the appendices only need to name known Facts. The Master resume has no PDF. + **resume.zh.md / resume.en.md**: a YAML block between `---` lines (`candidate`, `job`, `role`, `lang`, `written`, and `role_profile`, the build date of the Role profile it started from), then the resume, written by `resume save` from what you give it: ```yaml @@ -366,7 +418,7 @@ Import never asks for or depends on a target Role. ### Follow-up questions -When you start working with a Candidate, run `questions ` and offer the open ones again, and run `role stale ` to offer rebuilding out-of-date Role profiles. Save the user's answers as a Source with `source add - --type interview`, cite them with `at: q-`, mark the questions answered in their report, and add or update Facts. +When you start working with a Candidate, run `questions ` and offer the open ones again, run `role stale ` to offer rebuilding out-of-date Role profiles, and offer to write the Master resume again when `candidate show ` reports it stale. Save the user's answers as a Source with `source add - --type interview`, cite them with `at: q-`, mark the questions answered in their report, and add or update Facts. ### Inferred Facts @@ -378,7 +430,7 @@ When new input contradicts a Fact, write the new Fact, set both to `state: confl ### View, update, archive -- `candidate show `: profile summary, Facts by kind and evidence level, conflicts, top Tags, open follow-up questions, a Strategy summary and the Roles with their profile state. +- `candidate show `: profile summary, Facts by kind and evidence level, conflicts, top Tags, open follow-up questions, a Strategy summary, whether the Master resume is current, and the Roles with their profile state. - Update basics by editing `profile.yml`, then `validate`. - `candidate archive ` removes a Candidate from searches; `candidate restore ` brings them back. Never delete a Candidate folder. @@ -408,6 +460,23 @@ Each Evaluation compares one Job snapshot with one Candidate under the Role that 7. **No fitting Role**: offer to create a Role from the Job: its title (add it to `glossary.yml`), requirements from its must-haves and nice-to-haves with their Tags, `origin: job` and the Job id. Run `role new` only when the user agrees. 8. **Refine Roles**: when `evaluation save` reports proposed changes, run `role refine `. It proposes Tags that two or more Jobs evaluated under the Role require and no requirement has (a must-have when at least half of those Jobs list it as one), and assumed or Job requirements those Jobs also ask for. Show them to the user, apply the accepted ones with `--accept`, then rebuild the Role profile. +### Write the Master resume + +The Master resume writes out every usable Fact of a Candidate as one complete resume, in Chinese and English. It is internal: the user reads it to review and confirm the Facts, and extracts for specific contexts start from it. It is never sent. Write it when the user asks, and again when it is stale. + +1. **Plan**: `master plan ` shows the Candidate's Strategy without its Roles section, every usable Fact grouped by organization, newest first, and by kind, with its period, evidence and missing fields, the Facts never to use, the Glossary and the header. Add any company, title, school or location still missing from `glossary.yml`. +2. **Write** every usable Fact into a section, or list it under `left_out` with the reason, such as the Strategy leaving that experience out. + - **Summary**: a headline and a few sentences, not tied to a Role: years and fields, signature strengths, representative results, background. Viewpoints in the Strategy may shape its wording, but every sentence cites Facts. + - **Skills** in groups, each naming where it was used. **Highlights**: the 3–5 strongest results across organizations. + - **Experience**, newest first: one block per organization, a self-directed stretch such as independent development or study (`name`), or one project with titles at several companies (`roles`, one line per title, as a promotion within one company is shown). Each block has a context line (what the organization or project is), a scope line (team size, ownership, reporting line), achievements grouped under headings by project or theme with the most impactful first, and a tech line. + - Write each achievement in long form: the problem, the judgment or trade-off, the action, and the result with its measurement conditions. One line may combine the Facts that make up one achievement. + - Then projects, education, certificates and training, awards and publications, and languages. + - Wording may add context, the judgment behind an action and the impact a Fact states, but never raises a role ("took part in" never becomes "led") and never adds a number, title, date or skill. Follow the Strategy's resume guidance. +3. **Mark gaps**: add `gap` where a line lacks something, such as a result, a team size, a company's context or a date. Where no Fact can fill a line yet, give the item only a `gap`. +4. **Save**: pipe it to `master save `; `--replace` writes it again. +5. **Follow up**: ask the user about the Gaps appendix and save the answers as in Follow-up questions. The new Facts make the Master resume stale, so offer to write it again. +6. **Report** the two files, how many Facts it cites and leaves out, and its gaps. + ### Write resumes Write a Chinese and an English resume for an Application worth pursuing, after its Evaluation. diff --git a/skills/headhunter/scripts/hh.py b/skills/headhunter/scripts/hh.py index 916f98a..4223208 100644 --- a/skills/headhunter/scripts/hh.py +++ b/skills/headhunter/scripts/hh.py @@ -124,6 +124,20 @@ "skills": "Skills"}, } RESUME_FIELDS = ("headline", "summary", "experience", "projects", "education", "certificates", "skills") +MASTER_FIELDS = ("headline", "summary", "skills", "highlights", "experience", "projects", "education", "certificates", + "awards", "languages", "left_out") +MASTER_HEADINGS = { + "zh": {"summary": "專業摘要", "skills": "技能", "highlights": "核心亮點", "experience": "工作經歷", "projects": "專案", + "education": "學歷", "certificates": "證照與訓練", "awards": "獎項、發表、演講與專利", "languages": "語言", + "gaps": "待補", "left_out": "未寫入"}, + "en": {"summary": "Summary", "skills": "Skills", "highlights": "Highlights", "experience": "Experience", + "projects": "Projects", "education": "Education", "certificates": "Certificates and Training", + "awards": "Awards, Publications, Talks and Patents", "languages": "Languages", "gaps": "Gaps", + "left_out": "Left out"}, +} +MASTER_LABELS = {"zh": {"scope": "範疇:", "tech": "技術:"}, "en": {"scope": "Scope: ", "tech": "Tech: "}} +GAP_MARKS = {"zh": ("【待補:", "】"), "en": ("[To fill: ", "]")} +GAP_MARK = re.compile(r"\s*(?:【待補:[^】]*】|\[To fill: [^\]]*\])") BROWSERS = ( # Chrome, Chromium or Edge, used headless to print resumes to PDF "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", @@ -652,6 +666,13 @@ def err(message): err(f"resume {jid}: {path.name} must be resume.zh.md or resume.en.md") continue errors.extend(f"{name}: {e}" for e in check_resume(path, lang, by_id)) + masters = master_paths(folder) + if any(path.exists() for path in masters.values()): + for lang, path in masters.items(): + if path.exists(): + errors.extend(f"{name}: {e}" for e in check_master(path, lang, by_id)) + else: + err(f"master resume: {path.name} is missing; write both with master save --replace") for jid, path in application_dirs(folder): if not (path / "status.yml").exists(): if (path / "evaluation.md").exists() or list(path.glob("resume.*")): @@ -1687,20 +1708,92 @@ def check_resume(path: Path, lang: str, by_id: dict) -> list: if not cite: errors.append(f"{where}: line {n} cites no Fact; end it with or remove it: {text[:60]}") continue - ids = [fid for fid in cite.group(1).split(", ") if fid != "profile"] - for fid in ids: - if fid not in by_id: - errors.append(f"{where}: line {n} cites unknown Fact {fid}") - pool = " ".join(str(by_id.get(f, {}).get(k) or "") for f in ids for k in ("statement", "period")) - allowed = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", pool))) - used = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", text[:cite.start()]))) if ids else set() - for number in sorted(used - allowed): - errors.append(f"{where}: line {n} has the number {number}, which is not in {', '.join(ids)}") - if lang == "en" and HAN.search(text[:cite.start()]): - errors.append(f"{where}: line {n} has Chinese text; use the English names from glossary.yml: {text[:60]}") + errors += check_claim(where, n, text, text[:cite.start()], cite, lang, by_id) + return errors + + +def check_claim(where: str, n: int, text: str, claim: str, cite, lang: str, by_id: dict) -> list: + """Problems in one resume line that cites Facts: unknown Facts, numbers they do not hold, Chinese in English.""" + errors = [] + ids = [fid for fid in cite.group(1).split(", ") if fid != "profile"] + for fid in ids: + if fid not in by_id: + errors.append(f"{where}: line {n} cites unknown Fact {fid}") + pool = " ".join(str(by_id.get(f, {}).get(k) or "") for f in ids for k in ("statement", "period")) + allowed = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", pool))) + used = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", claim))) if ids else set() + for number in sorted(used - allowed): + errors.append(f"{where}: line {n} has the number {number}, which is not in {', '.join(ids)}") + if lang == "en" and HAN.search(text[:cite.start()]): + errors.append(f"{where}: line {n} has Chinese text; use the English names from glossary.yml: {text[:60]}") + return errors + + +def master_paths(folder: Path) -> dict: + return {lang: folder / f"master-resume.{lang}.md" for lang in RESUME_LANGS} + + +def check_master(path: Path, lang: str, by_id: dict) -> list: + """Problems in the Master resume's Markdown, checked like a Tailored resume's. A line that holds only a gap marker + cites nothing, and the Gaps and Left out appendices need only name known Facts.""" + where = f"master resume {lang}" + try: + front, body = read_job(path) + except HHError as exc: + return [str(exc)] + errors = [] + if front.get("lang") != lang: + errors.append(f"{where}: lang must be {lang}") + appendices = {f"## {MASTER_HEADINGS[lang][key]}" for key in ("gaps", "left_out")} + in_appendix = False + for n, line in enumerate(body.splitlines(), 1): + text = line.strip() + if text.startswith("## "): + in_appendix = text in appendices + continue + if not text or re.match(r"(?:#|####) ", text): + continue + if in_appendix: + errors += [f"{where}: line {n} names unknown Fact {fid}" for fid in re.findall(r"\bf-\d+\b", text) + if fid not in by_id] + if lang == "en" and HAN.search(text): + errors.append(f"{where}: line {n} has Chinese text: {text[:60]}") + continue + cite = CITATION.search(text) + claim = GAP_MARK.sub("", text[:cite.start()] if cite else text) + if cite: + errors += check_claim(where, n, text, claim, cite, lang, by_id) + continue + rest = re.sub(r"^-\s*", "", claim.strip()) + rest = next((rest[len(label):] for label in MASTER_LABELS[lang].values() if rest.startswith(label)), rest) + if GAP_MARK.search(text) and not re.sub(r"^\*\*[^*]+\*\*[::]\s*", "", rest).strip(): + continue + errors.append(f"{where}: line {n} cites no Fact; end it with or remove it: {text[:60]}") return errors +def master_stale(folder: Path, facts: list) -> list: + """Reasons the Master resume is out of date; empty when it is current.""" + path = master_paths(folder)["zh"] + if not path.exists(): + return ["not written yet"] + try: + front, _ = read_job(path) + except HHError as exc: + return [str(exc)] + built = front.get("built_from") or {} + covered = built.get("facts") or {} + current = {f.get("id"): f for f in facts if isinstance(f, dict)} + changed = [fid for fid, value in covered.items() if fid in current and digest(current[fid]) != str(value)] + removed = [fid for fid in covered if fid not in current] + uncovered = [fid for fid in current if fid not in covered and not fact_problem(current, fid)] + reasons = [f"{label}: {', '.join(ids)}" for label, ids in + (("changed", changed), ("removed", removed), ("not covered", uncovered)) if ids] + if built.get("strategy") != digest(strategy_guidance(folder)): + reasons.append("strategy.md changed") + return reasons + + def render_period(value, lang: str) -> str: start, sep, end = str(value).partition("..") if not sep: @@ -1708,6 +1801,109 @@ def render_period(value, lang: str) -> str: return f"{start} – {('至今' if lang == 'zh' else 'Present') if end in ('present', '') else end}" +class ResumeWriter: + """The Chinese and English lines of a resume, and every problem found while writing them, so that nothing is + written unless all checks pass. Tailored resumes and the Master resume both use it.""" + + def __init__(self, facts: list, glossary): + self.by_id = {f.get("id"): f for f in facts if isinstance(f, dict)} + self.pairs = glossary_pairs(glossary) + self.errors, self.texts = [], [] + self.lines = {lang: [] for lang in RESUME_LANGS} + + def cited(self, item, where) -> list: + """The usable Facts an item cites; a problem for each one it cannot cite.""" + ids = item.get("facts") if isinstance(item, dict) else None + if not isinstance(ids, list) or not ids: + self.errors.append(f"{where}: list the Facts it comes from") + return [] + good = [] + for fid in ids: + problem = fact_problem(self.by_id, fid) + if problem: + self.errors.append(f"{where}: {problem}") + else: + good.append(fid) + return good + + def bilingual(self, item, where, ids) -> dict: + """An item's zh and en text, whose numbers must all be in the Facts it cites.""" + text = {lang: str(item.get(lang) or "").strip() for lang in RESUME_LANGS} + if not all(text.values()): + self.errors.append(f"{where}: needs zh and en") + pool = " ".join(str(self.by_id[f].get(k) or "") for f in ids for k in ("statement", "period")) + allowed = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", pool))) + used = {n for value in text.values() for n in NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", value))} + for number in sorted(used - allowed): + self.errors.append(f"{where}: the number {number} is not in {', '.join(ids) or 'its Facts'}") + self.texts.append((where, text)) + return text + + def label(self, item, where) -> dict: + """A label's zh and en text, such as a heading; it states no claim, so it cites no Facts.""" + text = {lang: str(item.get(lang) or "").strip() if isinstance(item, dict) else "" for lang in RESUME_LANGS} + if not all(text.values()): + self.errors.append(f"{where}: needs zh and en") + self.texts.append((where, text)) + return text + + def add(self, lang_lines: dict, ids) -> None: + note = f" " if ids else "" + for lang in RESUME_LANGS: + self.lines[lang].append(lang_lines[lang] + note) + + def blank(self) -> None: + for lang in RESUME_LANGS: + self.lines[lang].append("") + + def heading(self, title: dict) -> None: + for lang in RESUME_LANGS: + self.lines[lang] += ["", f"## {title[lang]}", ""] + + def header(self, profile: dict) -> None: + """The name, location and contact from profile.yml.""" + name_en = str(profile.get("name_en") or "").strip() + if not name_en: + self.errors.append("profile.yml needs name_en for the English resume") + self.lines["zh"].append(f"# {profile.get('name')}") + self.lines["en"].append(f"# {name_en}") + header = {"zh": [], "en": []} + location = profile.get("location") + if location: + pair = self.pairs.get(str(location)) + english = pair[1] if pair else (str(location) if not HAN.search(str(location)) else None) + if not english: + self.errors.append(f"add the location {location!r} to glossary.yml as a term so the English resume can " + "name it") + header["zh"].append(str(location)) + header["en"].append(english or "") + contact = profile.get("contact") if isinstance(profile.get("contact"), dict) else {} + for value in [contact.get("email"), contact.get("phone"), *(contact.get("links") or [])]: + if value: + header["zh"].append(str(value)) + header["en"].append(str(value)) + if header["zh"]: + for lang in RESUME_LANGS: + self.lines[lang] += ["", " · ".join(header[lang]) + " "] + + def finish(self) -> None: + """Check Glossary names and English text across everything written, then raise if anything failed.""" + for zh, en in sorted(set(self.pairs.values())): + for where, text in self.texts: + if zh in text["zh"] and en.lower() not in text["en"].lower(): + self.errors.append(f"{where}: glossary.yml names {zh} as {en!r} in English") + elif term_used(en, text["en"]) and zh not in text["zh"] or term_used(en, text["zh"]): + self.errors.append(f"{where}: glossary.yml names {en} as {zh!r} in Chinese") + for where, text in self.texts: + if HAN.search(text["en"]): + self.errors.append(f"{where}: the English text has Chinese in it: {text['en'][:60]}") + if self.errors: + raise HHError("nothing written:\n " + "\n ".join(dict.fromkeys(self.errors))) + + def body(self, lang: str) -> str: + return re.sub(r"\n{3,}", "\n\n", "\n".join(self.lines[lang])).strip() + + # ---------------------------------------------------------------- applications @@ -2038,6 +2234,13 @@ def cmd_candidate_show(args): text = re.split(r"(?m)^## Roles\n", strategy.read_text(encoding="utf-8"))[0] lines = [line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")] print("Strategy: " + (" ".join(lines[:3]) if lines else "-")) + stale = master_stale(folder, facts) + if stale == ["not written yet"]: + print("Master resume: not written") + else: + master = master_paths(folder)["zh"] + written = read_job(master)[0].get("written") if master.exists() else None + print(f"Master resume: written {written}, " + (f"stale ({'; '.join(stale)})" if stale else "current")) roles = role_dirs(folder) print(f"Roles: {len(roles)}") for slug, path in roles: @@ -3043,12 +3246,7 @@ def cmd_resume_plan(args): print(f"{candidate_id(args.id)} {profile.get('name')} × {args.job} {job.get('title')} · {job.get('company')}") print(f"Evaluation: {evaluation.get('rating')} ({evaluation.get('score')}) under {slug}; Role profile built " f"{profile_md.get('built')} and current\n") - guidance = strategy_guidance(folder) - if guidance: - print("Follow the Candidate's Strategy (strategy.md without its Roles section):") - print("\n".join(f" {line}" if line else "" for line in guidance.splitlines()) + "\n") - else: - print("Strategy: nothing beyond the Roles yet; strategy.md holds no resume guidance\n") + print_strategy(folder) print("Start from the Role profile's positioning:") print(f" {positioning.get('headline')}\n {positioning.get('summary')}") print(f" Facts: {', '.join(positioning.get('facts') or [])}") @@ -3073,10 +3271,19 @@ def cmd_resume_plan(args): mark = "*" if fact["id"] in cited else " " details = " ".join(str(fact[k]) for k in ("period", "org") if fact.get(k)) print(f" {mark} {fact['id']} [{kind}, {fact.get('evidence')}] {details} {fact.get('statement')}") + print_unusable(facts, by_id) + print_glossary_and_header(profile, glossary) + + +def print_unusable(facts: list, by_id: dict) -> None: unusable = [f"{f['id']} ({f.get('state') if f.get('state') != 'active' else 'inferred, unconfirmed'})" for f in facts if fact_problem(by_id, f.get("id"))] if unusable: print(" Never use: " + ", ".join(unusable)) + + +def print_glossary_and_header(profile: dict, glossary) -> None: + """The Glossary names a resume must use, and what its header will show.""" print("\nGlossary:") for kind in GLOSSARY_KINDS: names = sorted({pair for pair in glossary_pairs(glossary, (kind,)).values()}) @@ -3092,6 +3299,15 @@ def cmd_resume_plan(args): f"contact {' · '.join(reach) or 'none; add contact (email, phone, links) to profile.yml'}") +def print_strategy(folder: Path) -> None: + guidance = strategy_guidance(folder) + if guidance: + print("Follow the Candidate's Strategy (strategy.md without its Roles section):") + print("\n".join(f" {line}" if line else "" for line in guidance.splitlines()) + "\n") + else: + print("Strategy: nothing beyond the Roles yet; strategy.md holds no resume guidance\n") + + def cmd_resume_save(args): root = data_dir() folder = find_candidate(root, args.id, archived=False) @@ -3105,64 +3321,11 @@ def cmd_resume_save(args): taxonomy = load_taxonomy(root) candidate = load_candidate(folder) profile, facts, glossary = candidate["profile"], candidate["facts"], candidate["glossary"] - by_id = {f.get("id"): f for f in facts if isinstance(f, dict)} - errors = [f"unknown field {key!r}; fields are {', '.join(RESUME_FIELDS)}" for key in data if key not in RESUME_FIELDS] - texts, lines = [], {lang: [] for lang in RESUME_LANGS} - - def cited(item, where) -> list: - ids = item.get("facts") if isinstance(item, dict) else None - if not isinstance(ids, list) or not ids: - errors.append(f"{where}: list the Facts it comes from") - return [] - good = [] - for fid in ids: - problem = fact_problem(by_id, fid) - if problem: - errors.append(f"{where}: {problem}") - else: - good.append(fid) - return good - - def bilingual(item, where, ids) -> dict: - text = {lang: str(item.get(lang) or "").strip() for lang in RESUME_LANGS} - if not all(text.values()): - errors.append(f"{where}: needs zh and en") - pool = " ".join(str(by_id[f].get(k) or "") for f in ids for k in ("statement", "period")) - allowed = set(NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", pool))) - used = {n for value in text.values() for n in NUMBER.findall(re.sub(r"(?<=\d),(?=\d{3})", "", value))} - for number in sorted(used - allowed): - errors.append(f"{where}: the number {number} is not in {', '.join(ids) or 'its Facts'}") - texts.append((where, text)) - return text - - def add(lang_lines: dict, ids) -> None: - note = f" " - for lang in RESUME_LANGS: - lines[lang].append(lang_lines[lang] + note) - - pairs = glossary_pairs(glossary) - name_en = str(profile.get("name_en") or "").strip() - if not name_en: - errors.append("profile.yml needs name_en for the English resume") - lines["zh"].append(f"# {profile.get('name')}") - lines["en"].append(f"# {name_en}") - header = {"zh": [], "en": []} - location = profile.get("location") - if location: - pair = pairs.get(str(location)) - english = pair[1] if pair else (str(location) if not HAN.search(str(location)) else None) - if not english: - errors.append(f"add the location {location!r} to glossary.yml as a term so the English resume can name it") - header["zh"].append(str(location)) - header["en"].append(english or "") - contact = profile.get("contact") if isinstance(profile.get("contact"), dict) else {} - for value in [contact.get("email"), contact.get("phone"), *(contact.get("links") or [])]: - if value: - header["zh"].append(str(value)) - header["en"].append(str(value)) - if header["zh"]: - for lang in RESUME_LANGS: - lines[lang] += ["", " · ".join(header[lang]) + " "] + writer = ResumeWriter(facts, glossary) + by_id, errors, lines = writer.by_id, writer.errors, writer.lines + cited, bilingual, add = writer.cited, writer.bilingual, writer.add + errors += [f"unknown field {key!r}; fields are {', '.join(RESUME_FIELDS)}" for key in data if key not in RESUME_FIELDS] + writer.header(profile) for key in ("headline", "summary"): item = data.get(key) @@ -3179,8 +3342,7 @@ def add(lang_lines: dict, ids) -> None: add({lang: f"**{text[lang]}**" if key == "headline" else text[lang] for lang in RESUME_LANGS}, ids) def section(key) -> None: - for lang in RESUME_LANGS: - lines[lang] += ["", f"## {RESUME_HEADINGS[lang][key]}", ""] + writer.heading({lang: RESUME_HEADINGS[lang][key] for lang in RESUME_LANGS}) companies, titles, schools = (glossary_pairs(glossary, (k,)) for k in ("company", "title", "school")) if data.get("experience"): @@ -3266,26 +3428,16 @@ def section(key) -> None: "en": "- " + ", ".join(str(t.get("en")) for t in skills)}, sorted(skill_facts, key=lambda f: id_number(f, "f") or 0)) for term, rid in lacking_terms(job, evaluation, facts, taxonomy).items(): - for where, text in texts: + for where, text in writer.texts: if any(term_used(term, value) for value in text.values()): errors.append(f"{where}: {term!r} belongs to {rid}, which the Candidate lacks; leave it out") - for zh, en in sorted(set(pairs.values())): - for where, text in texts: - if zh in text["zh"] and en.lower() not in text["en"].lower(): - errors.append(f"{where}: glossary.yml names {zh} as {en!r} in English") - elif term_used(en, text["en"]) and zh not in text["zh"] or term_used(en, text["zh"]): - errors.append(f"{where}: glossary.yml names {en} as {zh!r} in Chinese") - for where, text in texts: - if HAN.search(text["en"]): - errors.append(f"{where}: the English text has Chinese in it: {text['en'][:60]}") - if errors: - raise HHError("nothing written:\n " + "\n ".join(dict.fromkeys(errors))) + writer.finish() base.mkdir(parents=True, exist_ok=True) for lang in RESUME_LANGS: front = {"candidate": candidate_id(args.id), "job": args.job, "role": slug, "lang": lang, "written": today(), "role_profile": profile_md.get("built")} - body = re.sub(r"\n{3,}", "\n\n", "\n".join(lines[lang])).strip() + body = writer.body(lang) (base / f"resume.{lang}.md").write_text(f"---\n{hhyaml.dumps(front)}---\n\n{body}\n", encoding="utf-8") print(base / f"resume.{lang}.md") for line in write_pdfs(base, str(profile.get("name"))): @@ -3318,6 +3470,294 @@ def cmd_resume_pdf(args): print(line) +def cmd_master_plan(args): + root = data_dir() + folder = find_candidate(root, args.id, archived=False) + data = load_candidate(folder) + profile, facts, glossary = data["profile"], data["facts"], data["glossary"] + by_id = {f.get("id"): f for f in facts if isinstance(f, dict)} + stale = master_stale(folder, facts) + written = stale != ["not written yet"] + covered = set((read_job(master_paths(folder)["zh"])[0].get("built_from") or {}).get("facts") or {}) if written else set() + print(f"{candidate_id(args.id)} {profile.get('name')}: Master resume " + + ("not written yet" if not written else f"stale ({'; '.join(stale)})" if stale else "current") + "\n") + print_strategy(folder) + usable = [f for f in facts if isinstance(f, dict) and not fact_problem(by_id, f.get("id"))] + groups = {} + for fact in usable: + groups.setdefault(str(fact.get("org") or ""), []).append(fact) + + def latest(org: str) -> int: + ends = [period_months(f.get("period")) for f in groups[org]] + return max((10 ** 6 if end is None and start is not None else end or -1 for start, end in ends), default=-1) + + print(f"Write every one of these {len(usable)} Facts, or list it under left_out with a reason" + + (" (+ not in the current Master resume)" if written else "") + ":") + for org in sorted(groups, key=lambda o: (not o, -latest(o))): + print(f" {org or '(no organization)'}") + for kind in FACT_KINDS: + for fact in (f for f in groups[org] if f.get("kind") == kind): + mark = "+" if written and fact["id"] not in covered else " " + missing = f" (missing: {', '.join(fact['missing'])})" if fact.get("missing") else "" + print(f" {mark} {fact['id']} [{kind}, {fact.get('evidence')}] {fact.get('period') or '-'} " + f"{fact.get('statement')}{missing}") + print_unusable(facts, by_id) + print_glossary_and_header(profile, glossary) + + +def cmd_master_save(args): + root = data_dir() + folder = find_candidate(root, args.id, archived=False) + paths = master_paths(folder) + if any(p.exists() for p in paths.values()) and not args.replace: + raise HHError("the Master resume already exists; pass --replace to write it again") + data = read_payload(args) + if not isinstance(data, dict): + raise HHError("the Master resume must be a mapping") + candidate = load_candidate(folder) + profile, facts, glossary = candidate["profile"], candidate["facts"], candidate["glossary"] + writer = ResumeWriter(facts, glossary) + by_id, errors = writer.by_id, writer.errors + errors += [f"unknown field {key!r}; fields are {', '.join(MASTER_FIELDS)}" for key in data if key not in MASTER_FIELDS] + companies, titles, schools = (glossary_pairs(glossary, (k,)) for k in ("company", "title", "school")) + cited, body_ids, highlight_ids, gaps = set(), set(), {}, [] + + def items(key) -> list: + value = data.get(key) or [] + if key == "summary" and isinstance(value, dict): + value = [value] + if not isinstance(value, list): + errors.append(f"{key} must be a list") + return [] + return value + + def section(key) -> dict: + title = {lang: MASTER_HEADINGS[lang][key] for lang in RESUME_LANGS} + writer.heading(title) + return title + + def line(item, where, place, fmt=lambda lang, text: text) -> list: + """Write one line in both languages: its text and Facts, or only a gap marker; return the Facts it cites.""" + if not isinstance(item, dict): + errors.append(f"{where}: must be a mapping with zh, en and facts") + return [] + gap = item.get("gap") + if gap is not None: + gap = writer.label(gap, f"{where} gap") + if gap is None or any(item.get(lang) for lang in RESUME_LANGS): + ids = writer.cited(item, where) + text = writer.bilingual(item, where, ids) + else: + ids = writer.cited(item, where) if item.get("facts") else [] + text = {lang: "" for lang in RESUME_LANGS} + if gap is not None: + text = {lang: f"{text[lang]}{'' if lang == 'zh' else ' '}{GAP_MARKS[lang][0]}{gap[lang]}{GAP_MARKS[lang][1]}" + .strip() for lang in RESUME_LANGS} + gaps.append((place, gap, ids)) + cited.update(ids) + writer.add({lang: fmt(lang, text[lang]) for lang in RESUME_LANGS}, ids) + return ids + + def bullet(lang, text): + return f"- {text}" + + def at_org(ids, company) -> bool: + return any(by_id[f].get("org") and any(str(by_id[f]["org"]) in name or name in str(by_id[f]["org"]) + for name in company) for f in ids) + + def titled(item, where, ids, parts) -> None: + """Add the title and period of an Experience heading or title line, checked against its Facts.""" + if item.get("title"): + title = titles.get(str(item["title"])) + if not title: + errors.append(f"{where}: add the title {item['title']!r} to glossary.yml") + elif not any(t in str(by_id[f].get("statement")) for f in ids for t in title): + errors.append(f"{where}: the title {item['title']!r} is not in its Facts; leave it out or ask the user") + else: + parts["zh"].append(title[0]) + parts["en"].append(title[1]) + if item.get("period") is not None: + if str(item["period"]) not in {str(by_id[f].get("period")) for f in ids}: + errors.append(f"{where}: period must be the period of one of its Facts") + for lang in RESUME_LANGS: + parts[lang].append(render_period(item["period"], lang)) + + writer.header(profile) + headline = data.get("headline") + if not isinstance(headline, dict): + errors.append("headline is required, with zh, en and facts") + else: + writer.blank() + line(headline, "headline", {lang: "" for lang in RESUME_LANGS}, lambda lang, text: f"**{text}**") + summary = items("summary") + if not summary: + errors.append("summary is required: one or more sentences, each with zh, en and facts") + place = section("summary") + for n, item in enumerate(summary, 1): + line(item, f"summary {n}", place) + + if items("skills"): + place = section("skills") + for n, item in enumerate(items("skills"), 1): + where = f"skills {n}" + group = writer.label(item.get("label"), f"{where} label") if isinstance(item, dict) and item.get("label") else None + line(item, where, place, (lambda lang, text, g=group: f"- **{g[lang]}**{':' if lang == 'zh' else ': '}{text}") + if group else bullet) + + if items("highlights"): + place = section("highlights") + for n, item in enumerate(items("highlights"), 1): + highlight_ids[f"highlights {n}"] = line(item, f"highlights {n}", place, bullet) + + if items("experience"): + section("experience") + for n, block in enumerate(items("experience"), 1): + where = f"experience {n}" + if not isinstance(block, dict): + errors.append(f"{where}: must be a mapping") + continue + ids = writer.cited(block, where) + org, name = block.get("org"), block.get("name") + if bool(org) == bool(name): + errors.append(f"{where}: give org, a company in glossary.yml, or name, for a self-directed stretch") + continue + if org: + company = companies.get(str(org)) + if not company: + errors.append(f"{where}: add the company {org!r} to glossary.yml") + continue + if not at_org(ids, company): + errors.append(f"{where}: cite a Fact at {org}") + parts = {"zh": [company[0]], "en": [company[1]]} + else: + label = writer.label(name, f"{where} name") + parts = {lang: [label[lang]] for lang in RESUME_LANGS} + titled(block, where, ids, parts) + place = {lang: " · ".join(parts[lang][:2 if block.get("title") else 1]) for lang in RESUME_LANGS} + cited.update(ids) + body_ids.update(ids) + writer.add({lang: f"### {' · '.join(parts[lang])}" for lang in RESUME_LANGS}, ids) + writer.blank() + for m, role in enumerate(block.get("roles") or [], 1): + role_where = f"{where} role {m}" + role_ids = writer.cited(role, role_where) + company = companies.get(str(role.get("org") or "")) if isinstance(role, dict) else None + if not company: + errors.append(f"{role_where}: give org, a company in glossary.yml") + continue + if not at_org(role_ids, company): + errors.append(f"{role_where}: cite a Fact at {role.get('org')}") + role_parts = {"zh": [company[0]], "en": [company[1]]} + titled(role, role_where, role_ids, role_parts) + cited.update(role_ids) + body_ids.update(role_ids) + writer.add({lang: f"- {' · '.join(role_parts[lang])}" for lang in RESUME_LANGS}, role_ids) + if block.get("roles"): + writer.blank() + for key in ("context", "scope"): + if block.get(key) is not None: + body_ids.update(line(block[key], f"{where} {key}", place, + lambda lang, text, k=key: MASTER_LABELS[lang].get(k, "") + text)) + for m, group in enumerate(block.get("groups") or [], 1): + group_where = f"{where} group {m}" + if not isinstance(group, dict): + errors.append(f"{group_where}: must be a mapping with bullets") + continue + writer.blank() + if group.get("heading"): + heading = writer.label(group["heading"], f"{group_where} heading") + writer.add({lang: f"#### {heading[lang]}" for lang in RESUME_LANGS}, []) + writer.blank() + if not group.get("bullets"): + errors.append(f"{group_where}: needs bullets") + for k, item in enumerate(group.get("bullets") or [], 1): + body_ids.update(line(item, f"{group_where} bullet {k}", place, bullet)) + if block.get("tech") is not None: + writer.blank() + body_ids.update(line(block["tech"], f"{where} tech", place, + lambda lang, text: MASTER_LABELS[lang]["tech"] + text)) + writer.blank() + + for key in ("projects", "education", "certificates", "awards", "languages"): + if items(key): + place = section(key) + for n, item in enumerate(items(key), 1): + where = f"{key} {n}" + lead, period = {lang: [] for lang in RESUME_LANGS}, None + if key == "education" and isinstance(item, dict): + ids = [f for f in item.get("facts") or [] if not fact_problem(by_id, f)] + if item.get("school"): + school = schools.get(str(item["school"])) + if not school: + errors.append(f"{where}: add the school {item['school']!r} to glossary.yml") + continue + if not any(s in str(by_id[f].get("statement")) for f in ids for s in school): + errors.append(f"{where}: the school is not in its Facts") + lead = {lang: [school[RESUME_LANGS.index(lang)]] for lang in RESUME_LANGS} + period = item.get("period") + if period is not None and str(period) not in {str(by_id[f].get("period")) for f in ids}: + errors.append(f"{where}: period must be the period of one of its Facts") + found = line(item, where, place, lambda lang, text, lead=lead, period=period: "- " + " · ".join( + lead[lang] + [text] + ([render_period(period, lang)] if period is not None else []))) + if key == "projects": + body_ids.update(found) + + left = {} + for n, entry in enumerate(items("left_out"), 1): + where = f"left_out {n}" + ids = entry.get("facts") if isinstance(entry, dict) else None + if not isinstance(ids, list) or not ids: + errors.append(f"{where}: list the Facts it leaves out") + continue + reason = writer.label(entry, where) + for fid in ids: + problem = fact_problem(by_id, fid) + if problem: + errors.append(f"{where}: {problem}; only active, sourced Facts need listing") + elif fid in cited: + errors.append(f"{where}: {fid} is cited by a line; leave it out of left_out") + else: + left[fid] = reason + uncovered = [f["id"] for f in facts if isinstance(f, dict) and not fact_problem(by_id, f.get("id")) + and f["id"] not in cited and f["id"] not in left] + if uncovered: + errors.append(f"cite {', '.join(uncovered)} in a line, or list them under left_out with a reason") + for where, ids in highlight_ids.items(): + for fid in ids: + if fid not in body_ids: + errors.append(f"{where}: {fid} is cited by no Experience or Projects line; Highlights summarize them") + writer.finish() + + if gaps: + writer.heading({lang: MASTER_HEADINGS[lang]["gaps"] for lang in RESUME_LANGS}) + for place, gap, ids in gaps: + notes = {"zh": [], "en": []} + for fid in ids: + missing = by_id[fid].get("missing") or [] + notes["zh"].append(f"{fid} 缺 {'、'.join(missing)}" if missing else fid) + notes["en"].append(f"{fid} missing {', '.join(missing)}" if missing else fid) + for lang, colon, open_, sep, close in (("zh", ":", "(", ";", ")"), ("en", ": ", " (", "; ", ")")): + where = f"{place[lang]}{colon}" if place[lang] else "" + note = f"{open_}{sep.join(notes[lang])}{close}" if ids else "" + writer.lines[lang].append(f"- {where}{gap[lang]}{note}") + if left: + writer.heading({lang: MASTER_HEADINGS[lang]["left_out"] for lang in RESUME_LANGS}) + reasons = {} + for fid, reason in left.items(): + reasons.setdefault(tuple(reason.values()), []).append(fid) + for (zh, en), ids in reasons.items(): + writer.lines["zh"].append(f"- {', '.join(ids)}:{zh}") + writer.lines["en"].append(f"- {', '.join(ids)}: {en}") + + covered = sorted(cited | set(left), key=lambda f: id_number(f, "f") or 0) + built_from = {"strategy": digest(strategy_guidance(folder)), "facts": {fid: digest(by_id[fid]) for fid in covered}} + for lang in RESUME_LANGS: + front = {"candidate": candidate_id(args.id), "lang": lang, "written": today(), "built_from": built_from} + paths[lang].write_text(f"---\n{hhyaml.dumps(front)}---\n\n{writer.body(lang)}\n", encoding="utf-8") + print(paths[lang]) + print(f"{len(cited)} Facts cited, {len(left)} left out, {len(gaps)} gaps") + + def cmd_application_new(args): root = data_dir() folder = find_candidate(root, args.id, archived=False) @@ -4070,6 +4510,17 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("job") p.set_defaults(func=cmd_resume_pdf) + master = sub.add_parser("master", help="write the Candidate's Master resume: every usable Fact as one resume") + msub = master.add_subparsers(dest="action", required=True) + p = msub.add_parser("plan", help="show what the Master resume is written from, and whether it is current") + p.add_argument("id") + p.set_defaults(func=cmd_master_plan) + p = msub.add_parser("save", help="write master-resume.zh.md and master-resume.en.md from JSON or YAML on stdin") + p.add_argument("id") + p.add_argument("--file") + p.add_argument("--replace", action="store_true", help="write the Master resume again") + p.set_defaults(func=cmd_master_save) + job = sub.add_parser("job", help="read Listings and Jobs, and save Job snapshots") jsub = job.add_subparsers(dest="action", required=True) p = jsub.add_parser("listing", help="list the Jobs on a Listing page")