21 Commits
Author SHA1 Message Date
Ayobami Adegoke 09435eb1a5 fix(apply): run the page-count check Step 5b claimed Step 5d already ran (#476)
Step 5b's prose said "Page count is not checked here - that is
verify_pdf.py --pages's job, and Step 5d already runs it", and
verify_layout.py's docstring declines to measure page count for the same
reason. Step 5d's only verify_pdf.py call is --dump-text, and no step in
the workflow passed --pages at all (only the upstream-only CI assertion on
the stock examples does), so the hard 2-page CV and 1-page cover letter
limits were enforced by nothing but the visual PDF read - the "measure
first, then look" failure 5b was written to stop.

5b now runs verify_pdf.py --pages 2 on the CV and --pages 1 on the cover
letter ahead of verify_layout.py, names the ACTIVE-TEMPLATE page limit as
the substitute for a custom template, and the deferral sentence points at
those lines instead of at 5d.

tests/test_apply_page_count.py pins the invocations, their counts, their
order relative to the layout measurement, and that no prose defers the
check to a step that does not run it; all four cases fail on master.
2026-09-16 21:09:33 +02:00
Ayobami Adegoke b91c6125ec fix(salary): print the privacy footnote only when a row rendered N/A* (#475)
format_entry appended "* N/A = Too few employees to publish (privacy)"
under every category table, including one where every row has an index,
so the output asserted a suppression that never happened - the residual
noted on #470. Set a flag in the N/A* branch and print the footnote only
when it fired; a table with a suppressed row renders exactly as before.

Two FormatEntryTests cases pin both directions; the "omitted" case fails
on master.
2026-09-16 21:06:23 +02:00
Ayobami Adegoke 968fb1bd7e fix(salary): pair a bare Count/Index column pair instead of splitting it into two categories (#470)
The pairing loop required a non-empty derived category name on both
sides, but a header with no category word - "Count" + "Index", Danish
"Antal" + "Lønindeks" - strips to an empty name, so the simplest layout
the README advertises ("auto-pairs count/index columns") came out as two
unrelated standalone categories:

  {"count": {"count": 500}, "index": {"index": 108.5}}

salary_lookup then rendered a "Count  500  N/A*" row above an
"Index  -  108.5" row, and its footnote read the N/A* as "too few
employees to publish (privacy)" - a false statement about a company whose
headcount is in the file, shown during /apply's salary step. Any suffix
("Antal alle") made pairing work, which is why the shipped tests, all
suffixed, never saw it.

Pair on equal derived names, empty included, and give the nameless pair
the README's top-level category name (all_employees). A bare "Antal" with
no bare index column still stays a standalone count; named pairs
alongside are untouched.

Four new cases in test_convert_salary_excel.py, one of them rendering the
converter's output through salary_lookup.format_entry; all four fail
against the old pairing rule.
2026-09-16 06:47:45 +02:00
Oscar Madera e92f7d9065 feat(setup): add documents/projects/ ingestion for independent projects (Path A) (#468) 2026-09-16 06:47:15 +02:00
Jakob Stender Guldberg c93609cd22 fix(gmail-sync,outcome): keep free-form tracker notes free of CSV-breaking characters (#454) (#455)
* fix(gmail-sync): strip CSV-breaking characters from the email subject

Step 7a interpolated the raw subject line of a received email into the
`notes` column of job_search_tracker.csv. No writer here emits a quoted
tracker field, so an unescaped comma splits the row - for csv.DictReader
just as much as for a naive split, which matters because
tools/rank_state.py is the repo's only machine reader and uses exactly
that. `notes` is column 10 of 14, so a subject as ordinary as
"Re: Your application, Data Scientist" shifted cv_file,
cover_letter_file and source a column left. A line break is worse: it
ends the row and starts a second one.

The rule now sits on the append instruction itself rather than in a
general note a writer can miss. The subject survives verbatim in the
archive's outcome.md, which is Markdown and carries no such constraint.

/outcome Step 4 (outcome.md:195) is also free-form and has the same
exposure, but its text is model-authored in a turn the user is watching
rather than copied from third-party mail unattended. Left out
deliberately, to be filed separately.

* fix(outcome): keep the Step 4 tracker note free of CSV-breaking characters

/outcome Step 4 appended "a short dated note" to `notes` with no
constraint on its content, the same exposure /gmail-sync Step 7a had:
nothing quotes a tracker field, so `rejected, no feedback given` shifts
cv_file, cover_letter_file and source a column left under
csv.DictReader, and a line break ends the row. The append instruction
now requires a note with no commas, double quotes or line breaks.

Folded in at the maintainer's request on #455 so one entry and one rule
cover both free-form writers. The CSV-safety tests move out of
test_gmail_sync_command.py into test_tracker_notes_csv_safe.py, where a
CASES table pins the rule on each writer's append line.
2026-09-16 06:45:55 +02:00
Souptik Chakraborty 1b65f7198a fix(verify-layout): name both causes of a broken bounding-box extractor (#451) (#465)
verify_layout.py's skipped: message blamed only the xpdf-based pdftotext that
Git for Windows puts ahead of Poppler in PATH. A real Poppler can abort too:
26.0x before 26.05 crashes -bbox/-bbox-layout/-htmlmeta on a PDF whose Info
dictionary carries an empty string in any field, and hyperref writes exactly
that for every field it does not set. A lualatex/pdflatex document built with
hyperref and no \hypersetup{pdftitle=...} - an ordinary /add-template CV
template, not a malformed one - hits this with a working Poppler installed,
and the old message sent the reader to check their PATH when nothing was
wrong with it.

Named both causes in the raised message, the code comment above it, and the
module docstring. Behavior is unchanged: either cause still degrades to
skipped: exit 2, not exit 1, since a broken extractor is still not a broken
document.

Added test_poppler_abort_on_empty_info_string_names_that_cause_too, mocking
subprocess.run to raise CalledProcessError the way a real Poppler 26.0x abort
does (exit 1, a libc++abi out_of_range trace on stderr) rather than the
xpdf case's exit 99 - the two failures are the same exception type with
different exit codes and stderr text, so the message has to actually
distinguish them, not just catch the one class. Negative control: this test
fails against the pre-fix message with "'Poppler aborted' not found in
'...a pdftotext without -bbox is usually the xpdf build...'".

Thanks to @main-sounds-audio for the report and the isolated repro (which
field, which Poppler modes, five runs of five) that pinned this to Poppler's
own upstream regression (issue #1699, fixed in 26.05.0) rather than an
extraction-library swap.

Fixes #451
2026-09-16 06:43:20 +02:00
Oscar Madera 88d1b61047 feat(apply): verify posting source host against installed portals and known ATS apexes (#431) (#467)
- Add source host verification rule to apply.md Step 1 before drafting
- Check posting URL host against installed portals and six official ATS apexes
- Enforce fail-closed look-alike parsing (prefix, suffix, userinfo spoofing)
- Plainly flag unverified third-party hosts in evaluation output
- Add tests/test_apply_host_check.py and update CHANGELOG.md
2026-09-16 06:43:16 +02:00
Mads LorentzenandClaude Fable 5.1 27eb57ae93 docs(readme): say up front that Claude Code needs a paid plan or API credits (#456)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WPXraLZ4i7UW4xGn9tVcox
2026-09-14 18:50:00 +02:00
Mads LorentzenandClaude Fable 5.1 6de14ea85b changelog: fork-reconcile note on the #458 entry, PR number on the #463 entry
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WPXraLZ4i7UW4xGn9tVcox
2026-09-14 18:36:12 +02:00
NathanandNathan No-ot 9484a61831 fix(ci): skip the pristine-template guard in test_setup_command on forks (#463)
TemplatesStillCarryThePlaceholders asserts 05-cv-templates.md and 06-cover-letter-templates.md still carry their [FIRST_NAME]/[YOUR_*] tokens. /setup's documented Step 3.5/3.6 personalisation replaces exactly those tokens, so python-tests failed permanently on any personalized fork. Same @unittest.skipIf on GITHUB_REPOSITORY (defaulting to upstream when unset) as test_placeholder_integrity.py received in #407; that fix landed three days before this guard, which did not pick up the pattern.

Co-authored-by: Nathan No-ot <244263078+Nnoot02@users.noreply.github.com>
2026-09-14 18:35:23 +02:00
Ayobami Adegoke 73d52e0991 fix(verify_pdf): fold LaTeX's typographic substitutions before --contains; guard T1 fontenc for pdflatex (#385, #384) (#458)
`normalize_text()` folded whitespace only, so `--contains` compared what a
user types against what LaTeX renders. The stock CV compiled with the
documented lualatex command turns `'` into U+2019 and `--` into U+2013, so
`--contains "Master's degree"` and `--contains "2016-2024"` both reported
the keyword missing from a document that plainly contains it, through both
extractors. The documented remedy for a missing keyword is to add it, which
is the one thing the ATS section forbids.

Fold both sides at comparison time: NFC, then curly apostrophes and quotes
to ASCII, en/em dashes to `-`, no-break space to space. `--dump-text` still
writes the raw layer - that is what an ATS parses, and the date-range rule
in 05-cv-templates.md needs the raw en-dash visible there.

Separately, pdflatex without T1 font encoding stores accents decomposed
(`e` + U+0300). NFC repairs the pdftotext side of that, but pypdf reads the
same layer as `Z¨ urich` with a spacing accent, which no fold recovers.
moderncv 2.5 loads T1 itself under pdflatex; the apt-packaged 2.3.1 does
not - reproduced by compiling the template against moderncv v2.3.1 with
pdflatex (before: U+0308/U+0300 in pdftotext, `Z¨ urich` in pypdf; after:
U+00FC/U+00E8 in both). The template and the guide's preamble gain
`\ifpdftex\usepackage[T1]{fontenc}\fi`; the lualatex text layer is
byte-identical before and after.

Tests: ten new cases in test_verify_pdf.py (the fold-through and
normalize_text ones fail on the whitespace-only code) and a
test_latex_guidance.py guard that the fontenc line exists and stays inside
the pdflatex branch. framework_version 1.4.3 -> 1.4.4 on 05-cv-templates.md.

Reported and diagnosed by 9scorp4 in Discussions #385 and #384.
2026-09-14 18:30:50 +02:00
Ayobami Adegoke c2cd71ddee fix(jobdanmark-search): back off on 429/5xx in detail instead of failing on the first attempt (#460)
`detail` called fetch() directly rather than going through the CLI's own
request wrappers, so it had none of the three things apiFetch/apiPost
guarantee: no 429/5xx retry loop, a hand-inlined User-Agent that would
drift from the exported USER_AGENT, and a timeout no wrapper test covered.
A rate-limited detail page wrote API_ERROR and exited after ONE attempt;
jobnet, jobbank, jobindex, linkedin, and freehire all retry up to six
times on the same response. /scrape calls detail once per shortlisted
posting, so a burst that tripped jobdanmark's limiter dropped those
postings (no description, no deadline) while any other portal rode it out.

Demonstrated by driving the real command handler with a stubbed 429 and
instant timers: 1 fetch attempt and exit 1 before, 7 after (initial try
plus six retries, the contract's schedule).

Add htmlFetch to helpers.ts with the same backoff, timeout, and shared
User-Agent as the JSON wrappers - 404 returns null so detail keeps its
NOT_FOUND contract - and route detail through it. The retry-backoff,
user-agent, and request-timeout suites now cover all three wrappers, and
the new detail-backoff.test.ts exercises the handler path itself; its two
retry cases fail against the bare fetch().
2026-09-14 18:25:30 +02:00
Ayobami Adegoke c7bd494f11 fix(jobindex-search): reject non-jobindex detail URLs instead of fetching them verbatim (#447) (#448)
detail fetched any http(s) input verbatim with no host check and, when
the path didn't match, silently used the whole input URL as the job id -
a non-posting page came back as a well-formed fake posting with exit 0.
buildUrl now requires a jobindex.dk host and a /jobannonce/<id> path,
rebuilds the fetch URL from the extracted id, and exits 1 with the
stderr-JSON BAD_ID contract otherwise; bare ids stay permissive
slash-free tokens per the jobnet precedent. Eight cases in the new
detail-input.test.ts; the five rejection/canonicalization cases fail
against the verbatim unguarded extraction.
2026-09-10 20:36:54 +02:00
Jakob Stender Guldberg c776e3f2b6 fix(outcome,interview): glob the full <company>_<role> stem in the CV fallback (#444)
When a tracker row's cv_file/cover_letter_file columns are empty, /outcome
and /interview fell back to a company-prefix glob (cv/main_<company>*.tex).
/apply names drafts main_<company>_<role><CV_EXT>, so two roles at one
company both match that glob. /outcome copied whichever the filesystem
returned first into the archive as cv_draft.tex - the file whose stated
purpose is to record what was actually submitted - and its own "leave an
existing archived file" rule then made the wrong copy permanent.

Both fallbacks now glob cv/main_<company>_<role>.* and
cover_letters/cover_<company>_<role>.*, deriving the stem by the Subfolder
naming rule in documents/README.md rather than restating it, and skip with
a note instead of widening the search. Dropping the hardcoded .tex also
makes a template registered by /add-template findable.

The dot before the extension wildcard matters: a bare trailing * also
absorbs a longer role, so ML Engineer and ML Engineer II at one company
would collide the same way the company-prefix glob did.
2026-09-10 20:32:37 +02:00
cbd8a991ab feat(layout): measure compiled PDF layout instead of eyeballing it (#378)
* feat(layout): measure compiled PDF layout instead of eyeballing it

/apply Step 5b asks for layout properties and executes none of them: they are
checked by reading the rendered page, which is exactly how they get missed.

The failure that motivates this is silent under every existing check. A moderncv
\cventry renders as a tabular, so an entry is one unbreakable block; when it does
not fit in the space left, the whole entry moves to the next page and leaves a
hole behind. The document still compiles, still reports the expected page count,
and still passes tools/verify_pdf.py. Observed in the wild at 273pt, roughly 19
blank lines, mid-page, on a CV whose visual read looked fine.

tools/verify_layout.py reports per page where the text starts and stops, bottom
whitespace as a share of page height, and the largest gap between lines, then
exits 1 on a hole over 100pt, a non-final page ending more than 25% early, body
text colliding with the page-number footer, a final page more than 35% empty, or
an entry header or section heading stranded at a page break.

Page count is deliberately not checked here - verify_pdf.py --pages already does
that, and two implementations of one rule drift. Geometry comes from Poppler
pdftotext -bbox, already a dependency; a missing Poppler exits 2 with "skipped:"
rather than failing the run.

Tests build synthetic Page/Line geometry, so the suite needs neither Poppler nor
a LaTeX toolchain and runs on the existing 3.10-3.14 matrix.

* fix(layout): survive Windows encoding and a pdftotext without -bbox

Review found two failures on the repo's primary platform:

subprocess.run(..., text=True) decoded pdftotext's UTF-8 output with the
Windows ANSI codepage and crashed on the stock cv/main_example.pdf. It now
passes encoding="utf-8" with errors="replace" at the call site, matching the
fix verify_pdf.py already carries from #369.

Git for Windows ships an xpdf-based pdftotext that shadows Poppler in a
default PATH and has no -bbox flag; it exited 99, the CalledProcessError
escaped, and the run ended in exit 1 - indistinguishable from a real layout
problem, which would send /apply chasing a phantom hole. That now routes to
the existing "skipped:" exit 2 path with a message naming the likely cause,
covered by three tests on the extractor-failure path.

Also from review:

- .claude/settings.json and security_guards.py gain the verify_layout.py
  permission entries. apply.md Step 5b runs the tool on every /apply, so
  without them every run prompts.
- The docstring and CHANGELOG no longer call Poppler a dependency
  verify_pdf.py relies on. Since #369 verify_pdf prefers pypdf and Poppler is
  the fallback; word bboxes have no pypdf equivalent, so this is the one step
  that still wants it, and that is now what the text says.
- Docstring and apply.md state that the thresholds are calibrated for the
  stock moderncv and cover.cls geometry, and that the shipped example CV
  fails the thin-final-page rule by design.
- largest_gap documents that it measures top-to-top, so a tall line inflates
  the gap by its own height - over-detection, the safe direction.
- The test module imports via tools.verify_layout like test_verify_pdf.py
  instead of sys.path.insert.

* fix(verify_layout): quote only the first stderr line in the skip message (#378)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013fqqLgQSnwgWkv98twQhHi

---------

Co-authored-by: Mads Lorentzen <madslorentzen_17@hotmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 19:26:49 +02:00
8c81edc330 fix(scrape): make seen_jobs.json keys a pure function of the posting (#441)
* fix(scraper): make seen_jobs.json keys a pure function of the posting, and clean up the drift

The dedup key was prose only ("<url_or_company_title_key>"), so different
/scrape runs slugified company+title differently and the state file
accumulated two failures: keys carrying "&", "/", "," and ":" that break
the archive-folder path /apply and /outcome derive from company+role
(documents/README.md's subfolder rule exists because of exactly this),
and the same posting stored twice under two different truncations of a
long title (two Deloitte entries, one job, one URL).

tools/job_key.py makes the key a pure, deterministic function of
company+title+url: a strict allowlist slug, length-capped with a hash of
the full slug so truncation never collides across runs, and a fallback
to the portal's numeric job id when a non-Latin title slugifies to
nothing (a real prior entry, "securion_", would have collided with
every future non-Latin posting from that company).

--audit finds both failure classes in an existing seen_jobs.json without
guessing at a fix: malformed keys (real damage), a legacy three-part
company_title_location shape (harmless but not what the current rule
produces, so it silently re-duplicates on the next scrape), and
duplicate URLs. Ran it against this workspace's file and re-keyed the 15
entries it found - 7 malformed, 8 legacy-shape - verified byte-for-byte
against the pre-cleanup copy that no entry's data changed, only its key.

tests/test_job_key.py (16 tests) covers the slugify rules, the
truncation-hash behavior, both non-Latin fallback paths, and the audit
CLI's exit codes.

* fix(scrape): call the key helper from Step 4 instead of slugifying ad hoc

The helper added in the previous commit is only load-bearing if the spec
calls it. Step 4 described the key as prose ("<url_or_company_title_key>"),
which is what let each run slugify its own way. Step 4 now names the
command, and the schema shows the key's provenance.

Renumbers the trailing list item; no other behaviour in the step changes.

* docs(changelog): record the job-key rule under Unreleased

* fix(scrape): preserve dedup continuity across key rule

* changelog: note that existing seen_jobs.json entries need no migration (#441)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013fqqLgQSnwgWkv98twQhHi

---------

Co-authored-by: nox <nox@Mac.home>
Co-authored-by: Mads Lorentzen <madslorentzen_17@hotmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 16:25:15 +02:00
Mads LorentzenandClaude Fable 5.1 ccf786bdf2 changelog: move the #437 and #439 entries out of the released 1.7.1 section
Both branches predate the v1.7.1 cut, so their hunks' context pointed at the
old [Unreleased] "### Added" header, which the cut had rolled into [1.7.1].
The rebases applied cleanly and landed the entries inside the release. They
belong under [Unreleased].

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013fqqLgQSnwgWkv98twQhHi
2026-09-07 18:45:36 +02:00
Oscar Madera 6b07b13bd2 feat(commands): add GitHub repository project extraction to /expand (#437) 2026-09-07 18:43:59 +02:00
Oscar Madera 6176e6aaca feat(outcome): add stale sweep branch for batch-resolving quiet applications (#439)
* feat(outcome): add stale sweep branch for batch-resolving quiet applications

- Add /outcome stale [N] and /outcome sweep [N] to Step 0
- Offer stale sweep in Step 1.3 when rows are quiet 60+ days
- Add Step 2c Stale Sweep Branch with interactive all/select/skip confirmation
- Batch-resolve qualifying open applications to canonical no_response
- Update tracker status and append dated notes; update archive outcome.md
- Add Rule 9 to Important Rules
- Add tests/test_outcome_stale.py and update CHANGELOG.md

* test(outcome): drop auxiliary candidate filter from spec test per review
2026-09-07 18:41:16 +02:00
f8c606fb3d fix(jobnet-search): fallback to search endpoint on detail 404 for external ads (#432) (#435)
* fix(jobnet-search): fallback to search endpoint on detail 404 for external ads (#432)

* fix(jobnet-search): mark external detail fallback degraded and omit unknown fields

* changelog: add the #432 entry for the external-ad fallback

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013fqqLgQSnwgWkv98twQhHi

---------

Co-authored-by: Mads Lorentzen <madslorentzen17@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 18:38:15 +02:00
Instinctandnox ab5732138a fix(web-research): fail loudly when $SCRATCHPAD is unset instead of writing into the repo (#440)
* fix(web-research): fail loudly when $SCRATCHPAD is unset

The two runnable snippets in 09-web-research.md both start with
`cd "$SCRATCHPAD"`, but nothing in the repo ever sets that variable.
With it unset the command expands to `cd ""`, which succeeds and leaves
the shell in the current directory, so `page.html` and the extracted
text land wherever the command was run from. In practice that is the
repo checkout, which is exactly what the paragraph directly beneath the
curl block forbids: "Write to the session scratchpad directory, never
into the repo."

Guarding with `${SCRATCHPAD:?...}` turns a silent write into the repo
into an immediate, self-explaining failure. The message names where the
value comes from so the reader can set it and re-run.

* docs(changelog): record the $SCRATCHPAD guard under Unreleased

---------

Co-authored-by: nox <nox@Mac.home>
2026-09-07 18:34:46 +02:00
47 changed files with 2664 additions and 99 deletions
@@ -1,7 +1,7 @@
import { defineCommand, option } from "@bunli/core" import { defineCommand, option } from "@bunli/core"
import { z } from "zod" import { z } from "zod"
import { parse } from "node-html-parser" import { parse } from "node-html-parser"
import { BASE_URL, normalizeSlug, writeError } from "../helpers.js" import { BASE_URL, htmlFetch, normalizeSlug, writeError } from "../helpers.js"
import { extractCity, toContractDate } from "./search.js" import { extractCity, toContractDate } from "./search.js"
interface JsonLdJobPosting { interface JsonLdJobPosting {
@@ -241,26 +241,15 @@ export const detail = defineCommand({
const url = `${BASE_URL}/job/${slug}` const url = `${BASE_URL}/job/${slug}`
try { try {
const response = await fetch(url, { // htmlFetch carries the portal contract's 429/5xx backoff, the request
headers: { // timeout, and the shared User-Agent; a bare fetch() here had none.
"Accept": "text/html,application/xhtml+xml", const html = await htmlFetch(url)
"User-Agent": "Mozilla/5.0 (compatible; jobdanmark-cli/1.0)",
},
signal: AbortSignal.timeout(15000),
})
if (response.status === 404) { if (html === null) {
writeError("Job not found", "NOT_FOUND") writeError("Job not found", "NOT_FOUND")
process.exit(1) process.exit(1)
} }
if (!response.ok) {
writeError(`API request failed: ${response.status} ${response.statusText}`, "API_ERROR")
process.exit(1)
}
const html = await response.text()
if (signal.aborted) return if (signal.aborted) return
const output = parseJobPostingFromHtml(html, slug, url) const output = parseJobPostingFromHtml(html, slug, url)
@@ -64,6 +64,45 @@ export async function apiPost<T>(path: string, body: unknown): Promise<T> {
throw new Error("API request failed after max retries") throw new Error("API request failed after max retries")
} }
/**
* Fetch a rendered jobdanmark.dk page as text, with the same 429/5xx backoff,
* request timeout, and User-Agent as apiFetch/apiPost. `detail` reads HTML
* rather than the JSON API; it used to call fetch() directly with none of the
* three, so a rate-limited detail page failed on the first 429 while every
* other portal's detail command retried. Returns null on 404 so the caller
* keeps its own NOT_FOUND contract.
*/
export async function htmlFetch(url: string): Promise<string | null> {
const maxRetries = 6
let delay = 500
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const response = await fetch(url, {
headers: {
"Accept": "text/html,application/xhtml+xml",
"User-Agent": USER_AGENT,
},
signal: AbortSignal.timeout(15000),
})
if (response.status === 429 || response.status >= 500) {
if (attempt === maxRetries) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
}
const jitter = Math.floor(Math.random() * 500)
await new Promise((resolve) => setTimeout(resolve, delay + jitter))
delay = Math.min(delay * 2, 5000)
continue
}
if (response.status === 404) {
return null
}
if (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
}
return response.text()
}
throw new Error("API request failed after max retries")
}
export function writeError(error: string, code: string): void { export function writeError(error: string, code: string): void {
process.stderr.write(JSON.stringify({ error, code }) + "\n") process.stderr.write(JSON.stringify({ error, code }) + "\n")
} }
@@ -0,0 +1,134 @@
import { afterEach, describe, expect, test } from "bun:test";
import { detail } from "../src/commands/detail";
// The portal contract requires backoff on 429/5xx, and `/scrape` calls
// `detail` once per shortlisted posting - a burst that trips the rate limiter
// is exactly when it matters. The handler used to call fetch() directly with
// no retry loop: on a 429 it wrote API_ERROR and exited after ONE attempt,
// while every other portal's detail command retried. These tests drive the
// real command handler (not the wrapper in isolation) with a stubbed fetch,
// instant timers, and process.exit turned into a throw so the exit path can
// be asserted. On the pre-fix handler the first test sees 1 call and an exit.
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
const originalExit = process.exit;
const originalLog = console.log;
const originalStderrWrite = process.stderr.write;
afterEach(() => {
globalThis.fetch = originalFetch;
globalThis.setTimeout = originalSetTimeout;
process.exit = originalExit;
console.log = originalLog;
process.stderr.write = originalStderrWrite;
});
const JSON_LD_PAGE = `<!doctype html><html><head>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"JobPosting",
"title":"Data Engineer","datePosted":"2026-09-01","hiringOrganization":{"@type":"Organization","name":"Acme"},
"description":"Build pipelines."}</script></head><body></body></html>`;
function instantTimers() {
globalThis.setTimeout = ((fn: () => void) =>
originalSetTimeout(fn, 0)) as unknown as typeof setTimeout;
}
function stubFetch(responses: Array<() => Response>): { calls: number } {
const state = { calls: 0 };
globalThis.fetch = (async () => {
const i = Math.min(state.calls, responses.length - 1);
state.calls++;
return responses[i]();
}) as unknown as typeof fetch;
return state;
}
function captureOutput(): { stdout: string[]; stderr: string[] } {
const out = { stdout: [] as string[], stderr: [] as string[] };
console.log = ((...args: unknown[]) => out.stdout.push(args.join(" "))) as typeof console.log;
process.stderr.write = ((chunk: string | Uint8Array) => {
out.stderr.push(String(chunk));
return true;
}) as typeof process.stderr.write;
return out;
}
function firstStderrJson(out: { stderr: string[] }): unknown {
const firstLine = out.stderr.join("").trim().split("\n")[0];
return JSON.parse(firstLine);
}
class ExitCalled extends Error {
constructor(public code: number | undefined) {
super(`process.exit(${code})`);
}
}
function throwingExit() {
process.exit = ((code?: number) => {
throw new ExitCalled(code);
}) as unknown as typeof process.exit;
}
async function runDetail(slug: string): Promise<{ exit: number | null }> {
const handler = (detail as unknown as { handler: (ctx: unknown) => Promise<void> }).handler;
try {
await handler({ flags: { format: "json" }, positional: [slug], signal: new AbortController().signal });
return { exit: null };
} catch (err) {
if (err instanceof ExitCalled) return { exit: err.code ?? 0 };
throw err;
}
}
describe("detail backoff on the real handler path", () => {
test("retries a 429 and returns the posting on the next attempt", async () => {
instantTimers();
throwingExit();
const out = captureOutput();
const state = stubFetch([
() => new Response("", { status: 429, statusText: "Too Many Requests" }),
() => new Response(JSON_LD_PAGE, { status: 200 }),
]);
const result = await runDetail("data-engineer-acme");
expect(result.exit).toBeNull();
expect(state.calls).toBe(2);
const parsed = JSON.parse(out.stdout.join("\n")) as { title: string; slug: string };
expect(parsed.title).toBe("Data Engineer");
expect(parsed.slug).toBe("data-engineer-acme");
expect(out.stderr.join("")).toBe("");
});
test("gives up after the initial attempt plus six retries and exits 1 with API_ERROR", async () => {
instantTimers();
throwingExit();
const out = captureOutput();
const state = stubFetch([() => new Response("", { status: 503, statusText: "Service Unavailable" })]);
const result = await runDetail("data-engineer-acme");
expect(result.exit).toBe(1);
expect(state.calls).toBe(7);
const err = firstStderrJson(out) as { code: string; error: string };
expect(err.code).toBe("API_ERROR");
expect(err.error).toMatch(/503/);
});
test("a 404 is not retried and still reports NOT_FOUND", async () => {
throwingExit();
const out = captureOutput();
const state = stubFetch([() => new Response("", { status: 404 })]);
const result = await runDetail("gone");
expect(result.exit).toBe(1);
expect(state.calls).toBe(1);
// The handler's own catch block sees the throwing process.exit stub and
// writes a second line - a test artifact, not CLI behaviour. The first
// stderr line is the contract.
expect(firstStderrJson(out)).toEqual({ error: "Job not found", code: "NOT_FOUND" });
});
});
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test"; import { afterEach, describe, expect, test } from "bun:test";
import { apiFetch, apiPost } from "../src/helpers"; import { apiFetch, apiPost, htmlFetch } from "../src/helpers";
// A stalled upstream connection (accepted socket, no response) would otherwise // A stalled upstream connection (accepted socket, no response) would otherwise
// hang the CLI forever - fetch has no default timeout. Assert both request // hang the CLI forever - fetch has no default timeout. Assert both request
@@ -21,6 +21,17 @@ describe("request timeout", () => {
expect(init?.signal).toBeInstanceOf(AbortSignal); expect(init?.signal).toBeInstanceOf(AbortSignal);
}); });
test("htmlFetch passes an AbortSignal timeout to fetch", async () => {
let init: RequestInit | undefined;
globalThis.fetch = (async (_url: string | URL | Request, i?: RequestInit) => {
init = i;
return new Response("<html></html>", { status: 200 });
}) as unknown as typeof fetch;
await htmlFetch("https://jobdanmark.dk/job/x");
expect(init?.signal).toBeInstanceOf(AbortSignal);
});
test("apiPost passes an AbortSignal timeout to fetch", async () => { test("apiPost passes an AbortSignal timeout to fetch", async () => {
let init: RequestInit | undefined; let init: RequestInit | undefined;
globalThis.fetch = (async (_url: string | URL | Request, i?: RequestInit) => { globalThis.fetch = (async (_url: string | URL | Request, i?: RequestInit) => {
@@ -1,11 +1,13 @@
import { afterEach, describe, expect, test } from "bun:test"; import { afterEach, describe, expect, test } from "bun:test";
import { apiFetch, apiPost } from "../src/helpers"; import { apiFetch, apiPost, htmlFetch } from "../src/helpers";
// The portal contract requires backoff on 429/5xx. These tests pin the retry // The portal contract requires backoff on 429/5xx. These tests pin the retry
// loop offline: a stubbed fetch counts attempts, and a stubbed setTimeout // loop offline: a stubbed fetch counts attempts, and a stubbed setTimeout
// fires immediately so the exhaustion case does not sleep through the real // fires immediately so the exhaustion case does not sleep through the real
// 500ms -> 5s backoff schedule. apiFetch and apiPost carry separate copies of // 500ms -> 5s backoff schedule. apiFetch, apiPost, and htmlFetch carry separate
// the loop, so both are exercised to keep them from drifting apart. // copies of the loop, so all three are exercised to keep them from drifting
// apart. htmlFetch is the one `detail` uses: before it existed, detail called
// fetch() directly and a 429 failed on the first attempt (1 call, not 7).
const originalFetch = globalThis.fetch; const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout; const originalSetTimeout = globalThis.setTimeout;
@@ -33,6 +35,7 @@ function stubFetch(responses: Array<() => Response>): { calls: number } {
const wrappers: Array<[string, () => Promise<{ ok: boolean }>]> = [ const wrappers: Array<[string, () => Promise<{ ok: boolean }>]> = [
["apiFetch", () => apiFetch<{ ok: boolean }>("/x")], ["apiFetch", () => apiFetch<{ ok: boolean }>("/x")],
["apiPost", () => apiPost<{ ok: boolean }>("/x", {})], ["apiPost", () => apiPost<{ ok: boolean }>("/x", {})],
["htmlFetch", () => htmlFetch("https://jobdanmark.dk/job/x").then((html) => ({ ok: html !== null }))],
]; ];
for (const [name, call] of wrappers) { for (const [name, call] of wrappers) {
@@ -65,3 +68,12 @@ for (const [name, call] of wrappers) {
}); });
}); });
} }
describe("htmlFetch 404", () => {
test("returns null without retrying so detail keeps its NOT_FOUND contract", async () => {
const state = stubFetch([() => new Response("", { status: 404 })]);
expect(await htmlFetch("https://jobdanmark.dk/job/missing")).toBeNull();
expect(state.calls).toBe(1);
});
});
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test"; import { afterEach, describe, expect, test } from "bun:test";
import { apiFetch, apiPost, USER_AGENT } from "../src/helpers"; import { apiFetch, apiPost, htmlFetch, USER_AGENT } from "../src/helpers";
// Bun's fetch injects an anonymous default User-Agent (Bun/1.3.10) when code // Bun's fetch injects an anonymous default User-Agent (Bun/1.3.10) when code
// sets none. This CLI should say who is asking, in the honest style jobindex // sets none. This CLI should say who is asking, in the honest style jobindex
@@ -46,3 +46,17 @@ describe("apiPost user agent", () => {
expect(headerValue(init?.headers, "Content-Type")).toBe("application/json"); expect(headerValue(init?.headers, "Content-Type")).toBe("application/json");
}); });
}); });
describe("htmlFetch user agent", () => {
test("sends the shared User-Agent and asks for HTML", async () => {
let init: RequestInit | undefined;
globalThis.fetch = (async (_url: string | URL | Request, i?: RequestInit) => {
init = i;
return new Response("<html></html>", { status: 200 });
}) as unknown as typeof fetch;
await htmlFetch("https://jobdanmark.dk/job/x");
expect(headerValue(init?.headers, "User-Agent")).toBe(USER_AGENT);
expect(headerValue(init?.headers, "Accept")).toContain("text/html");
});
});
@@ -60,23 +60,38 @@ function stripTags(html: string): string {
} }
/** /**
* Extract job ID from URL or return as-is if already an ID * Parse a detail invocation's <id|url> into a canonical fetch target, or null.
*
* This is the gate between a stored (untrusted) URL and a network fetch, so it
* must never trust the raw string: the previous version fetched any http(s)
* URL verbatim and, when the path didn't match, used the whole input URL as
* the id - a non-posting page (a redirect target, a look-alike host, the
* homepage) came back as a well-formed fake posting with exit 0 (#447). A URL
* input now needs a jobindex.dk host (apex or subdomain) and a
* /jobannonce/<id> path, and the fetch URL is rebuilt from the extracted id -
* the canonical short form the bare-id path always used. A bare id stays a
* permissive scheme- and slash-free token (the jobnet precedent): the server
* 404s unknowns loudly, which is the honest failure. Exported for tests.
*/ */
function extractIdFromUrl(url: string): string { export function buildUrl(idOrUrl: string): { url: string; id: string } | null {
// Match IDs like h1647303, r13677312, etc. const trimmed = idOrUrl.trim()
const match = url.match(/\/jobannonce\/([a-zA-Z]\d+)/) if (/^https?:\/\//i.test(trimmed)) {
if (match) return match[1] let host: string
return url try {
} host = new URL(trimmed).hostname.toLowerCase()
} catch {
function buildUrl(idOrUrl: string): { url: string; id: string } { return null
if (idOrUrl.startsWith("http")) { }
const id = extractIdFromUrl(idOrUrl) if (host !== "jobindex.dk" && !host.endsWith(".jobindex.dk")) return null
return { url: idOrUrl, id } // Match IDs like h1647303, r13677312, etc.
const match = trimmed.match(/\/jobannonce\/([a-zA-Z]\d+)/)
if (!match) return null
return { url: `${BASE_URL}/jobannonce/${match[1]}`, id: match[1] }
} }
// It's a bare ID if (/^[a-zA-Z0-9_-]+$/.test(trimmed)) {
const url = `${BASE_URL}/jobannonce/${idOrUrl}` return { url: `${BASE_URL}/jobannonce/${trimmed}`, id: trimmed }
return { url, id: idOrUrl } }
return null
} }
const DANISH_MONTHS: Record<string, string> = { const DANISH_MONTHS: Record<string, string> = {
@@ -262,7 +277,15 @@ export const detail = defineCommand({
process.exit(1) process.exit(1)
} }
const { url, id } = buildUrl(idArg) const parsed = buildUrl(idArg)
if (!parsed) {
writeError(
`Could not parse a jobindex job id or jobannonce URL from "${idArg}"`,
"BAD_ID",
)
process.exit(1)
}
const { url, id } = parsed
try { try {
const html = await htmlFetch(url) const html = await htmlFetch(url)
@@ -0,0 +1,52 @@
import { describe, expect, test } from "bun:test";
import { buildUrl } from "../src/commands/detail";
// buildUrl is the gate between a stored (untrusted) URL and a network fetch.
// It must yield a canonical jobindex fetch target or null (-> BAD_ID) - never
// the raw input. The unguarded version fetched any http(s) URL verbatim and,
// when the path didn't match, used the whole input URL as the id, so a
// non-posting page came back as a well-formed fake posting with exit 0 (#447).
describe("jobindex detail input parsing", () => {
test("canonical URL with title slug", () => {
expect(buildUrl("https://www.jobindex.dk/jobannonce/h1647303/senior-data-engineer")).toEqual({
url: "https://www.jobindex.dk/jobannonce/h1647303",
id: "h1647303",
});
});
test("trailing slash and query string variants", () => {
expect(buildUrl("https://www.jobindex.dk/jobannonce/r13677312/")?.id).toBe("r13677312");
expect(buildUrl("https://www.jobindex.dk/jobannonce/h1647303?utm_source=x")?.id).toBe("h1647303");
});
test("jobindex subdomains and bare apex are accepted", () => {
expect(buildUrl("https://it.jobindex.dk/jobannonce/h1647303")?.id).toBe("h1647303");
expect(buildUrl("https://jobindex.dk/jobannonce/h1647303")?.id).toBe("h1647303");
});
test("a bare id builds the canonical URL (server 404s unknowns loudly)", () => {
expect(buildUrl("h1647303")).toEqual({
url: "https://www.jobindex.dk/jobannonce/h1647303",
id: "h1647303",
});
});
test("an off-host URL is rejected, not fetched", () => {
expect(buildUrl("https://evil.example/jobannonce/h1647303")).toBeNull();
});
test("look-alike and userinfo hosts are rejected", () => {
expect(buildUrl("https://jobindex.dk.evil.example/jobannonce/h1647303")).toBeNull();
expect(buildUrl("https://www.jobindex.dk@evil.example/jobannonce/h1647303")).toBeNull();
});
test("an own-host URL without a jobannonce id is rejected (the fake-posting repro)", () => {
expect(buildUrl("https://www.jobindex.dk/")).toBeNull();
});
test("garbage bare input is rejected", () => {
expect(buildUrl("not a slug!")).toBeNull();
expect(buildUrl("ftp://www.jobindex.dk/jobannonce/h1")).toBeNull();
});
});
@@ -1,6 +1,7 @@
import { defineCommand, option } from "@bunli/core" import { defineCommand, option } from "@bunli/core"
import { z } from "zod" import { z } from "zod"
import { apiFetch, normalizeJobId, writeError, stripHtml } from "../helpers.js" import { apiFetch, normalizeJobId, writeError, stripHtml } from "../helpers.js"
import type { JobAdRaw, SearchApiResponse } from "./search.js"
export interface DetailApiResponse { export interface DetailApiResponse {
id: string id: string
@@ -8,13 +9,14 @@ export interface DetailApiResponse {
body: string body: string
publicationDateTime: string publicationDateTime: string
unpublicationDateTime: string | null unpublicationDateTime: string | null
approvalStatus: string approvalStatus: string | null
views: number views: number | null
createdDateTime: string createdDateTime: string
updatedDateTime: string updatedDateTime: string
isAnonymousEmployer: boolean isAnonymousEmployer: boolean | null
hasLogo: boolean hasLogo: boolean
logoUrl: string | null logoUrl: string | null
isExternal?: boolean
employer: { employer: {
cvrNumber: string | null cvrNumber: string | null
pNumber: string | null pNumber: string | null
@@ -22,7 +24,7 @@ export interface DetailApiResponse {
hasCompanyLogo: boolean hasCompanyLogo: boolean
} }
job: { job: {
type: string type: string | null
address: { address: {
streetName: string | null streetName: string | null
city: string | null city: string | null
@@ -31,21 +33,21 @@ export interface DetailApiResponse {
countryCode: string countryCode: string
countryName: string countryName: string
} }
noFixedWorkplace: boolean noFixedWorkplace: boolean | null
isLimitedPeriod: boolean isLimitedPeriod: boolean | null
isDisabilityFriendly: boolean isDisabilityFriendly: boolean | null
isPartTime: boolean isPartTime: boolean | null
employmentDate: string | null employmentDate: string | null
conceptUriDa: string | null conceptUriDa: string | null
preferredLabelDa: string | null preferredLabelDa: string | null
driversLicenses: unknown[] driversLicenses: unknown[]
classifications: unknown[] classifications: unknown[]
shifts: unknown[] shifts: unknown[]
isFavorite: boolean isFavorite: boolean | null
} }
application: { application: {
deadlineDate: string | null deadlineDate: string | null
availablePositions: number availablePositions: number | null
contactPersons: Array<{ contactPersons: Array<{
firstNames: string | null firstNames: string | null
lastName: string | null lastName: string | null
@@ -53,12 +55,73 @@ export interface DetailApiResponse {
}> }>
url: string | null url: string | null
urlText: string | null urlText: string | null
isApplicationDeadlineASAP: boolean isApplicationDeadlineASAP: boolean | null
} }
organisationTypeId: number | null organisationTypeId: number | null
user: string | null user: string | null
} }
/**
* Maps a raw JobAd from the search endpoint to a DetailApiResponse.
* Used as a fallback when /FindJob/JobAdDetails/<id> returns 404 for external ads (#432).
*/
export function mapSearchAdToDetail(raw: JobAdRaw & { jobAdUrl?: string | null; jobAnnouncementTypeName?: string | null }): DetailApiResponse {
const street = raw.workPlaceAddress ? raw.workPlaceAddress.trim() : null
return {
id: raw.jobAdId,
title: raw.title,
body: raw.description ?? "",
publicationDateTime: raw.publicationDate ?? "",
unpublicationDateTime: null,
approvalStatus: null,
views: null,
createdDateTime: raw.publicationDate ?? "",
updatedDateTime: raw.publicationDate ?? "",
isAnonymousEmployer: null,
hasLogo: Boolean(raw.hasLogo),
logoUrl: raw.logoUrl ?? null,
isExternal: true,
employer: {
cvrNumber: raw.cvr ?? null,
pNumber: null,
name: raw.hiringOrgName ?? "",
hasCompanyLogo: Boolean(raw.hasLogo),
},
job: {
type: raw.jobAnnouncementTypeName ?? (raw.workHourPartTime != null ? (raw.workHourPartTime ? "PartTime" : "FullTime") : null),
address: {
streetName: street && street.length > 0 ? street : null,
city: raw.postalDistrictName ?? raw.municipality ?? null,
postalCode: raw.postalCode ? String(raw.postalCode) : null,
municipality: raw.municipality ?? null,
countryCode: raw.country === "Danmark" ? "DK" : (raw.country || "DK"),
countryName: raw.country || "Danmark",
},
noFixedWorkplace: null,
isLimitedPeriod: null,
isDisabilityFriendly: null,
isPartTime: raw.workHourPartTime != null ? Boolean(raw.workHourPartTime) : null,
employmentDate: null,
conceptUriDa: raw.conceptUriDa ?? null,
preferredLabelDa: raw.occupation ?? null,
driversLicenses: [],
classifications: [],
shifts: [],
isFavorite: raw.isFavorite != null ? Boolean(raw.isFavorite) : null,
},
application: {
deadlineDate: raw.applicationDeadline ?? null,
availablePositions: null,
contactPersons: [],
url: raw.jobAdUrl && raw.jobAdUrl.trim().length > 0 ? raw.jobAdUrl.trim() : null,
urlText: null,
isApplicationDeadlineASAP: raw.applicationDeadlineStatus ? raw.applicationDeadlineStatus === "NotDisclosed" : null,
},
organisationTypeId: null,
user: null,
}
}
/** /**
* Normalize a raw detail response before any output format sees it. * Normalize a raw detail response before any output format sees it.
* *
@@ -99,30 +162,53 @@ export const detail = defineCommand({
process.exit(1) process.exit(1)
} }
let data: DetailApiResponse | null = null
try { try {
const data = prepareDetail( data = prepareDetail(
await apiFetch<DetailApiResponse>(`/FindJob/JobAdDetails/${id}`, { await apiFetch<DetailApiResponse>(`/FindJob/JobAdDetails/${id}`, {
incrementViews: "false", incrementViews: "false",
}), }),
) )
if (signal.aborted) return
if (flags.format === "json") {
console.log(JSON.stringify(data, null, 2))
} else if (flags.format === "table") {
outputTable(data)
} else {
outputPlain(data)
}
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : String(err) const message = err instanceof Error ? err.message : String(err)
if (message.includes("404") || message.includes("Not Found")) { if (message.includes("404") || message.includes("Not Found")) {
writeError("Job ad not found", "NOT_FOUND") // Fallback for external ads: JobAdDetails returns 404 for ads with isExternal: true,
// but /FindJob/Search returns the full ad object including HTML description (#432).
try {
const searchResult = await apiFetch<SearchApiResponse>("/FindJob/Search", {
searchString: id,
resultsPerPage: "5",
pageNumber: "1",
orderType: "PublicationDate",
})
const match = searchResult.jobAds?.find((ad) => ad.jobAdId === id)
if (match) {
process.stderr.write("note: detail endpoint returned 404; retrieved external posting summary from search endpoint\n")
data = prepareDetail(mapSearchAdToDetail(match))
}
} catch {
// If fallback search fails, fall through to NOT_FOUND
}
if (!data) {
writeError("Job ad not found", "NOT_FOUND")
process.exit(1)
}
} else { } else {
writeError(message, "API_ERROR") writeError(message, "API_ERROR")
process.exit(1)
} }
process.exit(1) }
if (signal.aborted || !data) return
if (flags.format === "json") {
console.log(JSON.stringify(data, null, 2))
} else if (flags.format === "table") {
outputTable(data)
} else {
outputPlain(data)
} }
}, },
}) })
@@ -131,13 +217,13 @@ function outputTable(data: DetailApiResponse): void {
console.log(`ID: ${data.id}`) console.log(`ID: ${data.id}`)
console.log(`Title: ${data.title}`) console.log(`Title: ${data.title}`)
console.log(`Employer: ${data.employer.name}`) console.log(`Employer: ${data.employer.name}`)
console.log(`Type: ${data.job.type}`) console.log(`Type: ${data.job.type ?? "-"}`)
console.log(`City: ${data.job.address.city ?? "-"}`) console.log(`City: ${data.job.address.city ?? "-"}`)
console.log(`Postal: ${data.job.address.postalCode ?? "-"}`) console.log(`Postal: ${data.job.address.postalCode ?? "-"}`)
console.log(`Country: ${data.job.address.countryName}`) console.log(`Country: ${data.job.address.countryName}`)
console.log(`Published: ${data.publicationDateTime}`) console.log(`Published: ${data.publicationDateTime}`)
console.log(`Deadline: ${data.application.deadlineDate ?? "-"}`) console.log(`Deadline: ${data.application.deadlineDate ?? "-"}`)
console.log(`Positions: ${data.application.availablePositions}`) console.log(`Positions: ${data.application.availablePositions ?? "-"}`)
console.log(`Apply URL: ${data.application.url ?? "-"}`) console.log(`Apply URL: ${data.application.url ?? "-"}`)
} }
@@ -152,7 +238,7 @@ export function formatDetailPlain(data: DetailApiResponse): string {
`Location: ${data.job.address.city ?? "-"}, ${data.job.address.countryName}`, `Location: ${data.job.address.city ?? "-"}, ${data.job.address.countryName}`,
`Published: ${data.publicationDateTime}`, `Published: ${data.publicationDateTime}`,
`Deadline: ${data.application.deadlineDate ?? "-"}`, `Deadline: ${data.application.deadlineDate ?? "-"}`,
`Positions: ${data.application.availablePositions}`, `Positions: ${data.application.availablePositions ?? "-"}`,
] ]
if (data.application.url) { if (data.application.url) {
@@ -0,0 +1,88 @@
import { describe, expect, test } from "bun:test"
import { mapSearchAdToDetail } from "../src/commands/detail"
import type { JobAdRaw } from "../src/commands/search"
describe("mapSearchAdToDetail (Issue #432 external ad fallback)", () => {
const sampleAd: JobAdRaw & { jobAdUrl?: string; jobAnnouncementTypeName?: string } = {
jobAdId: "ext-123",
title: "AI Technical Artist",
hiringOrgName: "Tactile Games",
occupation: "Programmør og systemudvikler",
conceptUriDa: "http://data.star.dk/esco/occupation/8b6456a3-ae9a-45a0-a65b-fed797521753",
jobAnnouncementTypeName: "Almindelige vilkår",
workHourPartTime: false,
jobAdUrl: "https://job-boards.eu.greenhouse.io/tactilegames/jobs/4890782101",
hasLogo: true,
logoUrl: "/bff/logo/123",
workPlaceAddress: " Trekronergade 26 ",
cvr: "32319882",
description: "<p>Great job opening at Tactile.</p>",
applicationDeadline: "2026-12-05T00:00:00+01:00",
applicationDeadlineStatus: "ExpirationDate",
country: "Danmark",
municipality: "København",
postalCode: 2500,
postalDistrictName: "Valby",
publicationDate: "2026-09-05T00:00:00+02:00",
isExternal: true,
isSeen: false,
isFavorite: false,
}
test("maps all key fields correctly to DetailApiResponse format", () => {
const detail = mapSearchAdToDetail(sampleAd)
expect(detail.id).toBe("ext-123")
expect(detail.title).toBe("AI Technical Artist")
expect(detail.body).toBe("<p>Great job opening at Tactile.</p>")
expect(detail.publicationDateTime).toBe("2026-09-05T00:00:00+02:00")
expect(detail.isExternal).toBe(true)
expect(detail.views).toBeNull()
expect(detail.approvalStatus).toBeNull()
expect(detail.isAnonymousEmployer).toBeNull()
expect(detail.employer.name).toBe("Tactile Games")
expect(detail.employer.cvrNumber).toBe("32319882")
expect(detail.employer.hasCompanyLogo).toBe(true)
expect(detail.job.type).toBe("Almindelige vilkår")
expect(detail.job.address.streetName).toBe("Trekronergade 26")
expect(detail.job.address.city).toBe("Valby")
expect(detail.job.address.postalCode).toBe("2500")
expect(detail.job.address.municipality).toBe("København")
expect(detail.job.address.countryCode).toBe("DK")
expect(detail.job.address.countryName).toBe("Danmark")
expect(detail.job.isPartTime).toBe(false)
expect(detail.job.noFixedWorkplace).toBeNull()
expect(detail.job.isLimitedPeriod).toBeNull()
expect(detail.job.isDisabilityFriendly).toBeNull()
expect(detail.job.preferredLabelDa).toBe("Programmør og systemudvikler")
expect(detail.job.conceptUriDa).toBe("http://data.star.dk/esco/occupation/8b6456a3-ae9a-45a0-a65b-fed797521753")
expect(detail.application.deadlineDate).toBe("2026-12-05T00:00:00+01:00")
expect(detail.application.availablePositions).toBeNull()
expect(detail.application.url).toBe("https://job-boards.eu.greenhouse.io/tactilegames/jobs/4890782101")
expect(detail.application.isApplicationDeadlineASAP).toBe(false)
})
test("handles empty or whitespace address gracefully", () => {
const detail = mapSearchAdToDetail({
...sampleAd,
workPlaceAddress: " ",
postalDistrictName: null,
municipality: null,
postalCode: null,
})
expect(detail.job.address.streetName).toBeNull()
expect(detail.job.address.city).toBeNull()
expect(detail.job.address.postalCode).toBeNull()
expect(detail.job.address.municipality).toBeNull()
})
test("flags undisclosed deadline as ASAP", () => {
const detail = mapSearchAdToDetail({
...sampleAd,
applicationDeadlineStatus: "NotDisclosed",
})
expect(detail.application.isApplicationDeadlineASAP).toBe(true)
})
})
+41 -6
View File
@@ -44,13 +44,29 @@ python salary_lookup.py "<Company Name>" --json
If the posting specifies a city, add `--city "<City>"` to narrow results. Parse the JSON output and include the salary benchmark in the evaluation. If the tool is not configured or returns an error, skip the salary benchmark. If the posting specifies a city, add `--city "<City>"` to narrow results. Parse the JSON output and include the salary benchmark in the evaluation. If the tool is not configured or returns an error, skip the salary benchmark.
### Source Host Verification (when input is a URL)
Before proceeding to drafting, inspect the posting URL's hostname to verify provenance (#431). Classify the host into one of three categories:
1. **Installed portal board:** the host matches any configured job portal in `.agents/skills/` (e.g. `jobindex.dk`, `linkedin.com`, `jobnet.dk`, `jobbank.dk`, `jobdanmark.dk`, `freehire.me`, or any portal added by `/add-portal`).
2. **Known official ATS apex:** the host matches or is a valid subdomain of one of the six standard ATS domains:
- `greenhouse.io`
- `lever.co`
- `myworkdayjobs.com` (or `workday.com`)
- `ashbyhq.com`
- `smartrecruiters.com`
- `workable.com`
*Look-alike parsing:* the host must match the apex exactly or end with `.<apex>`. Look-alike prefix tricks (e.g. `evil-greenhouse.io`), suffix spoofing (e.g. `job-boards.greenhouse.io.evil.com`), userinfo tricks (`https://greenhouse.io@evil.com/`), and unfamiliar subdomains fail closed and must not be classified as an official ATS.
3. **Neither (Unverified host):** name the host plainly in the evaluation output as unverified (`⚠ Unverified source host: <hostname> - not an installed portal board or known ATS apex`). Alert the user to verify the employer and link legitimacy before committing time and tokens to drafting.
Present the evaluation to the user with: Present the evaluation to the user with:
1. **Skills match** - which required/preferred skills match vs. gaps 1. **Source host verification** - installed portal board, official ATS, or ⚠ unverified source host (named plainly)
2. **Experience match** - how work history maps to the role 2. **Skills match** - which required/preferred skills match vs. gaps
3. **Behavioral/culture match** - how behavioral profile fits the role/company culture 3. **Experience match** - how work history maps to the role
4. **Salary benchmark** - salary index for the company (if available) 4. **Behavioral/culture match** - how behavioral profile fits the role/company culture
5. **Overall fit score** and recommendation (strong fit / moderate fit / weak fit) 5. **Salary benchmark** - salary index for the company (if available)
6. **Overall fit score** and recommendation (strong fit / moderate fit / weak fit)
After presenting the evaluation, ask the user: After presenting the evaluation, ask the user:
> "Should I proceed with drafting the CV and cover letter for this role?" > "Should I proceed with drafting the CV and cover letter for this role?"
@@ -229,7 +245,26 @@ If either compile fails, fix the error and re-compile until clean.
### 5b. Inspect layout ### 5b. Inspect layout
Read both PDFs via the Read tool and verify: **Measure first, then look.** A visual read catches gross breakage but cannot tell you that a page is 40% empty, and the failure below survives both a clean compile and a correct page count:
```bash
python tools/verify_pdf.py cv/main_<company>_<role>.pdf --pages 2
python tools/verify_pdf.py cover_letters/cover_<company>_<role>.pdf --pages 1
python tools/verify_layout.py cv/main_<company>_<role>.pdf
python tools/verify_layout.py cover_letters/cover_<company>_<role>.pdf
```
The two `--pages` lines are the page-count check: exactly 2 pages for the CV and exactly 1 for the cover letter (the hard limits in `05-cv-templates.md` and `06-cover-letter-templates.md`), exit 1 otherwise. With a custom template active, substitute its declared **Page limit** from the `ACTIVE-TEMPLATE` block. Nothing else runs this check - `verify_layout.py` deliberately leaves page count to it, and Step 5d's extraction call passes no `--pages` - so if these lines are skipped, the page budget is enforced by nothing but the visual read below.
The layout script reports, per page, where the text starts and stops, bottom whitespace as a share of page height, and the largest vertical gap between lines. It exits 1 on: a hole over 100pt (~7 blank lines), a non-final page ending more than 25% early, body text colliding with the page-number footer, a final page more than 35% empty, and an entry header or section heading stranded at a page break. Page count is **not** checked here — that is `verify_pdf.py --pages`'s job, and the two `--pages` lines above run it.
The hole check is the one a visual read misses. A moderncv `\cventry` renders as a `tabular`, so it is an **unbreakable block**: when it does not fit in the space left, the whole entry jumps to the next page and leaves a hole behind, while the document still compiles and still reports the right page count. Fix it by shortening the entry that follows the hole, not by stretching the page.
If Poppler is missing, or the `pdftotext` first in PATH is the xpdf build Git for Windows ships (no `-bbox`), the script exits 2 with `skipped:` — note the degraded mode in the Step 6 report and rely on the visual inspection alone. Exit 2 is never a layout verdict.
The thresholds are calibrated for the stock moderncv and `cover.cls` geometry; a template registered via `/add-template` may report a phantom hole above a footer the 90pt band does not cover.
Then read both PDFs via the Read tool and verify:
**CV (`cv/main_<company>_<role>.pdf`):** **CV (`cv/main_<company>_<role>.pdf`):**
- [ ] Exactly 2 pages (not 1, not 3) - [ ] Exactly 2 pages (not 1, not 3)
+16 -2
View File
@@ -55,6 +55,7 @@ Look up the GitHub username from `01-candidate-profile.md`. If a GitHub URL or u
2. For each repository found: 2. For each repository found:
- Fetch the repository README - Fetch the repository README
- Note: name, description, primary language(s), topics/tags, any frameworks or libraries mentioned in the README - Note: name, description, primary language(s), topics/tags, any frameworks or libraries mentioned in the README
- If the repository represents an independent technical project (not an empty stub or uncustomized fork), extract a project summary (problem domain, tech stack, and demonstrable technical results) for consideration under Independent Projects
3. Also retrieve the full repository list if available (to catch unpinned repos) 3. Also retrieve the full repository list if available (to catch unpinned repos)
If no GitHub username or URL is found in the profile, skip this source and note it was skipped. If no GitHub username or URL is found in the profile, skip this source and note it was skipped.
@@ -108,19 +109,25 @@ After enriching all items, build a deduplicated competency map. Group findings i
**Domain Knowledge** (subject matter expertise: geophysics, ML, NLP, etc.) **Domain Knowledge** (subject matter expertise: geophysics, ML, NLP, etc.)
**Methods and Practices** (agile, version control, reproducibility, testing, etc.) **Methods and Practices** (agile, version control, reproducibility, testing, etc.)
**Soft / Behavioral** (leadership, communication, collaboration signals from references and project descriptions) **Soft / Behavioral** (leadership, communication, collaboration signals from references and project descriptions)
**Independent Projects & Portfolio** (distinct technical projects from GitHub with problem domain, tech stack, and key technical milestone)
For each competency, record: For each competency, record:
- The competency name - The competency name
- The source item it came from (e.g. "Coursera — Deep Learning Specialisation", "GitHub — repo-name", "Reference letter — Jens Jensen") - The source item it came from (e.g. "Coursera — Deep Learning Specialisation", "GitHub — repo-name", "Reference letter — Jens Jensen")
- Whether it came from direct lookup (A), inference (B), or both - Whether it came from direct lookup (A), inference (B), or both
For each project, record:
- Project name
- One-line summary: problem tackled, tech stack used, and verifiable outcome/impact
- Source (e.g. "GitHub — repo-name")
Remove anything already present in `01-candidate-profile.md` or `02-behavioral-profile.md`. Remove anything already present in `01-candidate-profile.md` or `02-behavioral-profile.md`.
--- ---
## Step 4: Present Grouped Summary ## Step 4: Present Grouped Summary
Present all new competencies for the user's review before writing anything. Format: Present all new competencies and project additions for the user's review before writing anything. Format:
``` ```
## /expand found [N] new competency signals across [M] sources ## /expand found [N] new competency signals across [M] sources
@@ -131,6 +138,11 @@ Source: [Course/cert name — Provider]
+ [Competency 2] + [Competency 2]
... ...
**PROJECTS & PORTFOLIO**
Source: [GitHub — repo-name]
+ [Project Name]: [Problem, stack, and outcome]
...
**GITHUB — [repo-name]** **GITHUB — [repo-name]**
Source: README + inferred from tech stack Source: README + inferred from tech stack
+ [Competency 1] + [Competency 1]
@@ -169,6 +181,7 @@ Wait for the user's response before writing anything.
Apply only the confirmed items. Use the Edit tool to add to the relevant sections of each file — do not rewrite entire files. Apply only the confirmed items. Use the Edit tool to add to the relevant sections of each file — do not rewrite entire files.
### Additions to `01-candidate-profile.md` ### Additions to `01-candidate-profile.md`
- Independent projects → append to the `## Independent Projects` section formatted as `- **[Project Name]**: [Description with stack and outcome] *(GitHub — repo-name)*`
- Technical skills (primary and secondary) → append to the Technical Skills section - Technical skills (primary and secondary) → append to the Technical Skills section
- Domain knowledge → append to the Domain Knowledge or Technical Skills section (match the existing structure) - Domain knowledge → append to the Domain Knowledge or Technical Skills section (match the existing structure)
- Methods and practices → append appropriately - Methods and practices → append appropriately
@@ -189,7 +202,7 @@ After writing, present:
## /expand Complete ## /expand Complete
### Added to 01-candidate-profile.md ### Added to 01-candidate-profile.md
[List each competency added, with source] [List each competency and independent project added, with source]
### Added to 02-behavioral-profile.md ### Added to 02-behavioral-profile.md
[List each behavioral signal added, with source] [List each behavioral signal added, with source]
@@ -214,3 +227,4 @@ After writing, present:
- **User confirms before writing.** The full competency map is shown and confirmed before a single file is touched. - **User confirms before writing.** The full competency map is shown and confirmed before a single file is touched.
- **Behavioral signals are labeled.** Anything inferred from tone, language, or indirect signals is marked as inferred so it is reviewed critically. - **Behavioral signals are labeled.** Anything inferred from tone, language, or indirect signals is marked as inferred so it is reviewed critically.
- **GitHub is fully scanned.** All public repositories are checked, not just pinned ones — unpinned repos often contain significant competency signals. - **GitHub is fully scanned.** All public repositories are checked, not just pinned ones — unpinned repos often contain significant competency signals.
- **Portfolio & projects grounded in code.** Independent projects added to the profile must reflect real projects found in public GitHub repositories — never fabricated project claims.
+3 -1
View File
@@ -124,7 +124,9 @@ Approving the whole batch in one reply is expected UX - the requirement is that
For every row the user approved: For every row the user approved:
1. **Tracker (`job_search_tracker.csv`):** update the matched row's `status` column per the Step 5 table, and append to `notes`: `<date> gmail-sync: <signal> ("<email subject>")`. Never restructure the CSV, reorder rows, or touch unrelated rows - same rule `/outcome` follows. The rewrite touches only `status`, `notes` (and `date` when the drafted-rule below fires): preserve every other field of the row, parsed or not, so the `deadline` column written by `/apply` Step 6b - or any column added in the future - is never blanked by a status sync. 1. **Tracker (`job_search_tracker.csv`):** update the matched row's `status` column per the Step 5 table, and append to `notes`: `<date> gmail-sync: <signal> ("<email subject>")`, **with every comma, double quote and line break deleted from the subject first**. No writer here emits a quoted tracker field and no reader unquotes one, so an unescaped comma splits the row identically for a naive split and for the `csv.DictReader` the shipped reader actually uses (`tools/rank_state.py`): `cv_file`, `cover_letter_file` and `source` each shift a column left. A line break is worse - it ends the row and starts a second one. The double quote is stripped as cheap insurance for the day something does quote a field; on today's readers it is harmless. The subject is a human-readable breadcrumb here, not data anything reads back - item 2 below keeps it verbatim in `outcome.md`, which is Markdown and carries no such constraint. This matters more than it looks: `/gmail-sync` is the only tracker writer that copies *third-party* text, and the only one that runs unattended, so nobody is watching the row it edits.
Never restructure the CSV, reorder rows, or touch unrelated rows - same rule `/outcome` follows. The rewrite touches only `status`, `notes` (and `date` when the drafted-rule below fires): preserve every other field of the row, parsed or not, so the `deadline` column written by `/apply` Step 6b - or any column added in the future - is never blanked by a status sync.
**If the matched row was still `drafted`,** also set `date` to the email's date. The employer replying proves the user submitted by hand without running `/outcome`, so the drafting date now in that column is wrong. The email's date is an upper bound on the real submission date, tight for an ack and loose for a rejection weeks later, which is why Step 6 shows it and lets the user supply the actual date instead. **If the matched row was still `drafted`,** also set `date` to the email's date. The employer replying proves the user submitted by hand without running `/outcome`, so the drafting date now in that column is wrong. The email's date is an upper bound on the real submission date, tight for an ack and loose for a rejection weeks later, which is why Step 6 shows it and lets the user supply the actual date instead.
2. **`outcome.md`:** tick the relevant stage checkbox (adding the date in parentheses) or update `Status`/`Date resolved` per the table. Append a dated entry to `## Notes`, never overwrite existing Notes history: 2. **`outcome.md`:** tick the relevant stage checkbox (adding the date in parentheses) or update `Status`/`Date resolved` per the table. Append a dated entry to `## Notes`, never overwrite existing Notes history:
+1 -1
View File
@@ -25,7 +25,7 @@ v1 preps for a **specific application**. Generic no-target practice is out of sc
- `job_posting.md` - the exact posting the user applied to - `job_posting.md` - the exact posting the user applied to
- `cv_draft.tex` and `cover_letter.tex` - what was actually submitted. **These are what the interviewer read**; every talking point must be consistent with their claims. - `cv_draft.tex` and `cover_letter.tex` - what was actually submitted. **These are what the interviewer read**; every talking point must be consistent with their claims.
- `outcome.md` - the stage reached so far and any recorded feedback from earlier stages. Feedback from stage N is the highest-value input for stage N+1 prep. - `outcome.md` - the stage reached so far and any recorded feedback from earlier stages. Feedback from stage N is the highest-value input for stage N+1 prep.
2. **Fallbacks** (the application may predate `/outcome`): posting via WebFetch on the tracker row's `source` URL, or ask the user to paste it; CV via `cv/main_<company>*.tex` and cover letter via `cover_letters/cover_<company>_*.tex`. State plainly which context is missing rather than guessing - and suggest `/outcome <company>` to build the archive for next time. 2. **Fallbacks** (the application may predate `/outcome`): posting via WebFetch on the tracker row's `source` URL, or ask the user to paste it; CV via `cv/main_<company>_<role>.*` and cover letter via `cover_letters/cover_<company>_<role>.*`, deriving `<company>_<role>` by the **Subfolder naming** rule in `documents/README.md`. **Never widen those globs to the company alone**: with two roles at one company it would prep you from the sibling role's documents. State plainly which context is missing rather than guessing - and suggest `/outcome <company>` to build the archive for next time.
3. **Ask the user what this interview is** (skip anything `outcome.md` already records): stage (phone screen / technical / case / final round), date, format (phone, video, onsite), and who is interviewing (names and titles, if known). 3. **Ask the user what this interview is** (skip anything `outcome.md` already records): stage (phone screen / technical / case / final round), date, format (phone, video, onsite), and who is interviewing (names and titles, if known).
4. **Read the frameworks once** - do not re-read them in later steps: 4. **Read the frameworks once** - do not re-read them in later steps:
- `.claude/skills/job-application-assistant/07-interview-prep.md` - `.claude/skills/job-application-assistant/07-interview-prep.md`
+51 -3
View File
@@ -22,6 +22,8 @@ Follow these steps **in order**.
- `followup` → enter the follow-up branch (Step 2b) over every quiet open application, using the default threshold of **10 days** - `followup` → enter the follow-up branch (Step 2b) over every quiet open application, using the default threshold of **10 days**
- `followup <N>`, e.g. `/outcome followup 14` → follow-up branch with an N-day threshold - `followup <N>`, e.g. `/outcome followup 14` → follow-up branch with an N-day threshold
- `followup <company>`, e.g. `/outcome followup acme` → draft a follow-up for that application now, regardless of threshold - `followup <company>`, e.g. `/outcome followup acme` → draft a follow-up for that application now, regardless of threshold
- `stale` or `sweep` → enter the stale application sweep branch (Step 2c) over open applications quiet for **60+ days**
- `stale <N>` or `sweep <N>`, e.g. `/outcome stale 90` → stale sweep branch with an N-day threshold
--- ---
@@ -33,7 +35,7 @@ Follow these steps **in order**.
``` ```
**If the file exists and its header does not end in `,deadline`, append `,deadline` to the header line only** - no data row is touched. Legacy rows then read as an empty deadline. This is the one edit to an existing tracker this command may make outside a matched row, and Step 4's "never restructure the CSV" governs that row, not this header line. **If the file exists and its header does not end in `,deadline`, append `,deadline` to the header line only** - no data row is touched. Legacy rows then read as an empty deadline. This is the one edit to an existing tracker this command may make outside a matched row, and Step 4's "never restructure the CSV" governs that row, not this header line.
2. **With an argument:** match rows case-insensitively on company (and role, if given). One match → proceed. Several → list them and ask. None → the application was made outside the workflow; collect company, role, date applied, channel, and posting URL from the user and add a tracker row. 2. **With an argument:** match rows case-insensitively on company (and role, if given). One match → proceed. Several → list them and ask. None → the application was made outside the workflow; collect company, role, date applied, channel, and posting URL from the user and add a tracker row.
3. **Without an argument:** list all rows whose status is not final (see **Tracker status vocabulary** below) as a numbered table (company, role, date applied, current status, deadline, days quiet, follow-ups sent) and ask which to update. The two derived columns come straight from existing data: **days quiet** counts from the row's `date` or the latest dated entry in `notes`, whichever is more recent; **follow-ups sent** counts the `followed up YYYY-MM-DD` markers in `notes`. If any open row is 10+ days quiet with fewer than two follow-ups sent, add one line under the table: "Some of these have gone quiet - want a follow-up draft? (Step 2b)". If every row is resolved, say so and stop. 3. **Without an argument:** list all rows whose status is not final (see **Tracker status vocabulary** below) as a numbered table (company, role, date applied, current status, deadline, days quiet, follow-ups sent) and ask which to update. The two derived columns come straight from existing data: **days quiet** counts from the row's `date` or the latest dated entry in `notes`, whichever is more recent; **follow-ups sent** counts the `followed up YYYY-MM-DD` markers in `notes`. If any open row is 10+ days quiet with fewer than two follow-ups sent, add one line under the table: "Some of these have gone quiet - want a follow-up draft? (Step 2b)". If any open rows are 60+ days quiet, also offer: "You have applications quiet for 60+ days — run `/outcome stale` to batch-resolve them (Step 2c)." If every row is resolved, say so and stop.
**`drafted` rows are listed but never counted as quiet** - nothing was sent, so nobody is late replying. List them under their own heading ("Drafted, not yet submitted"), leave **days quiet** and **follow-ups sent** blank, and keep them out of the follow-up offer above. **`drafted` rows are listed but never counted as quiet** - nothing was sent, so nobody is late replying. List them under their own heading ("Drafted, not yet submitted"), leave **days quiet** and **follow-ups sent** blank, and keep them out of the follow-up offer above.
@@ -110,11 +112,56 @@ If the user decides not to send, log nothing.
--- ---
## Step 2c: Stale Sweep Branch (batch-resolve quiet applications)
Enter this branch from the `stale` or `sweep` argument (Step 0), or from the suggestion under the open-pipeline table in Step 1.3. In an extended job hunt, applications that received no response accumulate and clutter the tracker, `/html-report` funnel metrics, and `/notion-sync`. This branch operationalizes batch-cleaning old quiet applications while keeping the user in full control.
**Candidates.** An application qualifies when its tracker `status` is open and submitted (`applied` or `interview`), the threshold has passed since its `date` (or since the latest dated entry in `notes`, whichever is more recent), and its status is neither final nor `drafted` (`drafted` applications were never submitted and cannot receive a response). Parse dates defensively — skip unparseable rows with a note.
**Threshold.** The default threshold is **60 days** quiet. If the user specified an integer `<N>` (e.g. `/outcome stale 90` or `/outcome sweep 45`), use N days instead.
**Presentation.** If no open applications exceed the threshold, report:
> "No open applications exceed the <N>-day quiet threshold. Your tracker is up to date!"
and stop.
Otherwise, present qualifying applications as a numbered table:
```
## Stale Applications ([K] quiet for [N]+ days)
| # | Company | Role | Date Applied | Days Quiet | Follow-ups Sent | Current Status | Proposed Status |
|---|---------|------|--------------|------------|-----------------|----------------|-----------------|
| 1 | Acme | SWE | 2026-05-10 | 118 | 2 | applied | no_response |
| 2 | Beta | MLE | 2026-06-01 | 96 | 1 | applied | no_response |
```
Then ask:
> **How would you like to resolve these applications?**
>
> - **`all`** — Mark all [K] applications as `no_response` and update archives
> - **`select`** — Specify which numbers to resolve (e.g. "1, 3" or "1-4")
> - **`skip`** — Cancel without making any changes
Wait for the user's explicit response before writing anything.
**Execution.** For each application the user confirms:
1. **Update Tracker:** update the row's `status` column to `no_response` (using the canonical spelling from **Tracker status vocabulary**). Append `stale resolved no_response (YYYY-MM-DD)` to `notes`. Follow Step 4's rule: never restructure the CSV, preserve all other columns intact.
2. **Update Archive:** derive `documents/applications/<company>_<role>/` per the **Subfolder naming** rule. If the folder exists, update or write `outcome.md` with:
- `**Status:** no_response`
- `**Date resolved:** YYYY-MM-DD`
- Append to `## Notes`: `- Stale resolution: marked no_response after [N] days quiet (YYYY-MM-DD)`
**Calibration Handoff.** If 3 or more applications were resolved in this sweep, continue to Step 5 to offer calibration handoff. Otherwise present a summary of resolved applications and stop.
---
## Step 3: Archive the Application Materials ## Step 3: Archive the Application Materials
Create or update `documents/applications/<company>_<role>/`. All content here is personal data - the folder is already gitignored (`documents/applications/**`), so nothing needs redacting. Create or update `documents/applications/<company>_<role>/`. All content here is personal data - the folder is already gitignored (`documents/applications/**`), so nothing needs redacting.
1. **`cv_draft.tex` and `cover_letter.tex`** - copy (never move) the submitted files. Locate them via the tracker row's `cv_file`/`cover_letter_file` columns; if those are empty, look for `cv/main_<company>*.tex` and `cover_letters/cover_<company>_*.tex`. If a file already exists in the archive, leave it - the archived version is what was actually submitted. If no draft files exist (application made outside `/apply`), skip with a note. 1. **`cv_draft.tex` and `cover_letter.tex`** - copy (never move) the submitted files. Locate them via the tracker row's `cv_file`/`cover_letter_file` columns; if those are empty, look for `cv/main_<company>_<role>.*` and `cover_letters/cover_<company>_<role>.*`, deriving `<company>_<role>` by the **Subfolder naming** rule in `documents/README.md`. **Never widen those globs to the company alone** - two roles at one company both match it, and the first hit wins silently. If a file already exists in the archive, leave it - the archived version is what was actually submitted. If nothing matches (application made outside `/apply`), skip with a note rather than widening the search: a sibling role's CV recorded as what you submitted is worse than no file at all.
2. **`job_posting.md`** - if it already exists, leave it. Otherwise try WebFetch on the tracker row's `source` URL and save the posting text, retrying a 403 with browser headers per `.claude/skills/job-application-assistant/09-web-research.md`. If the URL is dead (postings expire fast - this is exactly why the archive matters), ask the user to paste the posting, or write a stub noting the posting is unavailable. **Never reconstruct a posting from memory.** 2. **`job_posting.md`** - if it already exists, leave it. Otherwise try WebFetch on the tracker row's `source` URL and save the posting text, retrying a 403 with browser headers per `.claude/skills/job-application-assistant/09-web-research.md`. If the URL is dead (postings expire fast - this is exactly why the archive matters), ask the user to paste the posting, or write a stub noting the posting is unavailable. **Never reconstruct a posting from memory.**
3. **`outcome.md`** - write or update it in exactly the format documented in `documents/README.md`, so `/setup` Path A parses it without special cases: 3. **`outcome.md`** - write or update it in exactly the format documented in `documents/README.md`, so `/setup` Path A parses it without special cases:
@@ -145,7 +192,7 @@ Update rules: tick stage checkboxes as they are reached (add the date in parenth
## Step 4: Update the Tracker ## Step 4: Update the Tracker
Update the matched row's `status` column using the canonical spellings from **Tracker status vocabulary** above (e.g. `drafted` → `applied` → `interview` → `offer` → `hired` / `rejected` / `no_response` / `offer_declined` / `withdrawn`) and append a short dated note to the `notes` column. Never restructure the CSV, reorder rows, or touch other rows. The rewrite touches only the `status` and `notes` columns: preserve every other field of the row, parsed or not, so a value the row carries - the `deadline` written by `/apply` Step 6b, or any column added in the future - is never blanked by a status update. Update the matched row's `status` column using the canonical spellings from **Tracker status vocabulary** above (e.g. `drafted` → `applied` → `interview` → `offer` → `hired` / `rejected` / `no_response` / `offer_declined` / `withdrawn`) and append a short dated note to the `notes` column, **containing no commas, double quotes or line breaks**. No writer here emits a quoted tracker field, so a comma in the note shifts `cv_file`, `cover_letter_file` and `source` a column left for `csv.DictReader` (`tools/rank_state.py`) as much as for a naive split, and a line break ends the row - `rejected, no feedback given` is exactly the sentence that corrupts it; write `rejected - no feedback given`. `/gmail-sync` Step 7a applies the same rule to the email subjects it appends. Never restructure the CSV, reorder rows, or touch other rows. The rewrite touches only the `status` and `notes` columns: preserve every other field of the row, parsed or not, so a value the row carries - the `deadline` written by `/apply` Step 6b, or any column added in the future - is never blanked by a status update.
**Moving a row off `drafted`:** rows written by `/apply` Step 6b carry the date the documents were drafted, not the date they were sent. Whenever this step advances such a row to any other status - `applied`, or straight to `interview` or `rejected` when the user reports an outcome for something they submitted without recording it - overwrite its `date` column with the actual submission date. The `date` column is read as "applied on" by `/notion-sync` and drives `/html-report`'s year/season grouping and this command's own days-quiet count, so leaving the draft date in place would misreport the application. **Moving a row off `drafted`:** rows written by `/apply` Step 6b carry the date the documents were drafted, not the date they were sent. Whenever this step advances such a row to any other status - `applied`, or straight to `interview` or `rejected` when the user reports an outcome for something they submitted without recording it - overwrite its `date` column with the actual submission date. The `date` column is read as "applied on" by `/notion-sync` and drives `/html-report`'s year/season grouping and this command's own days-quiet count, so leaving the draft date in place would misreport the application.
@@ -193,3 +240,4 @@ If the recorded status is `hired`, congratulate the user warmly first - this is
6. **Follow-ups: draft only, never send.** The follow-up branch produces text for the user to send themselves. It never emails, messages, or submits anything, and it must not be wired to tools that do. 6. **Follow-ups: draft only, never send.** The follow-up branch produces text for the user to send themselves. It never emails, messages, or submits anything, and it must not be wired to tools that do.
7. **Follow-ups: no new claims.** Every substantive statement in a follow-up or thank-you note comes from the archived submitted materials. Rule 3 applies with no exceptions. 7. **Follow-ups: no new claims.** Every substantive statement in a follow-up or thank-you note comes from the archived submitted materials. Rule 3 applies with no exceptions.
8. **Maximum two follow-ups per application.** After the second silent follow-up, the honest move is recording the resolution, not persistence. 8. **Maximum two follow-ups per application.** After the second silent follow-up, the honest move is recording the resolution, not persistence.
9. **Stale sweep: user confirms before writing.** The stale sweep branch never marks applications as no_response automatically. It always presents the qualifying candidate list and waits for explicit user confirmation (all, select, or skip).
+6 -2
View File
@@ -20,7 +20,7 @@ If `$ARGUMENTS` is empty or does not contain a recognized scope keyword, ask:
> >
> - **`profile`** — Clears candidate data from the skill files (profile, behavioral, STAR examples, profile statements, personalized evaluation criteria, search queries). The framework structure, scoring framework, and writing rules are preserved. Use this to re-run `/setup` from scratch. > - **`profile`** — Clears candidate data from the skill files (profile, behavioral, STAR examples, profile statements, personalized evaluation criteria, search queries). The framework structure, scoring framework, and writing rules are preserved. Use this to re-run `/setup` from scratch.
> >
> - **`documents`** — Deletes all files you've placed in the `documents/` folder (CV PDFs, LinkedIn export, diplomas, references, pasted job postings, past applications). The folder structure and `README.md` are preserved. > - **`documents`** — Deletes all files you've placed in the `documents/` folder (CV PDFs, LinkedIn export, diplomas, references, project summaries, pasted job postings, past applications). The folder structure and `README.md` are preserved.
> >
> - **`all`** — Both of the above. > - **`all`** — Both of the above.
> >
@@ -86,7 +86,7 @@ cv/main_example.tex. This scope covers skill files only.
### If scope includes `documents`: ### If scope includes `documents`:
Use Glob to list all files present in `documents/cv/`, `documents/linkedin/`, `documents/diplomas/`, `documents/references/`, `documents/postings/`, and `documents/applications/`. Present as: Use Glob to list all files present in `documents/cv/`, `documents/linkedin/`, `documents/diplomas/`, `documents/references/`, `documents/projects/`, `documents/postings/`, and `documents/applications/`. Present as:
``` ```
## Documents reset will delete: ## Documents reset will delete:
@@ -103,6 +103,9 @@ documents/diplomas/
documents/references/ documents/references/
- [filename] or "(empty)" - [filename] or "(empty)"
documents/projects/
- [filename] or "(empty)"
documents/postings/ documents/postings/
- [filename] or "(empty)" - [filename] or "(empty)"
@@ -246,6 +249,7 @@ rm -f documents/cv/*
rm -f documents/linkedin/* rm -f documents/linkedin/*
rm -f documents/diplomas/* rm -f documents/diplomas/*
rm -f documents/references/* rm -f documents/references/*
rm -f documents/projects/*
rm -f documents/postings/* rm -f documents/postings/*
rm -rf documents/applications/*/ rm -rf documents/applications/*/
``` ```
+9 -4
View File
@@ -29,7 +29,7 @@ visibility cannot be determined — warn now and wait:
Wait for the user's confirmation before showing the path prompt. A private origin, no Wait for the user's confirmation before showing the path prompt. A private origin, no
origin, or a non-fork remote needs no warning — continue silently. origin, or a non-fork remote needs no warning — continue silently.
Then, before greeting the user, scan the `documents/` folder. Use Glob with `documents/**/*` and count files per subfolder (`cv/`, `linkedin/`, `diplomas/`, `references/`, `applications/`). Then, before greeting the user, scan the `documents/` folder. Use Glob with `documents/**/*` and count files per subfolder (`cv/`, `linkedin/`, `diplomas/`, `references/`, `projects/`, `applications/`).
Then welcome the user with a single message that lists three paths. The wording changes based on what was found. Then welcome the user with a single message that lists three paths. The wording changes based on what was found.
@@ -57,7 +57,7 @@ Then welcome the user with a single message that lists three paths. The wording
> >
> Three ways to start: > Three ways to start:
> >
> **Path A: Documents folder** (best signal if you have several materials) - Drop your CV / LinkedIn export / diplomas / reference letters in the `documents/` folder, then say "go". I'll read everything and build your profile from it. See `documents/README.md` for the folder layout. > **Path A: Documents folder** (best signal if you have several materials) - Drop your CV / LinkedIn export / diplomas / reference letters / project summaries in the `documents/` folder, then say "go". I'll read everything and build your profile from it. See `documents/README.md` for the folder layout.
> >
> **Path B: Single CV import** - Paste or @-mention a single CV/resume here. I'll extract it and ask follow-up questions for what's missing. > **Path B: Single CV import** - Paste or @-mention a single CV/resume here. I'll extract it and ask follow-up questions for what's missing.
> >
@@ -86,6 +86,7 @@ Use Glob with `documents/**/*` to scan the full tree. Print:
**linkedin/**: [list files, or "(empty)"] **linkedin/**: [list files, or "(empty)"]
**diplomas/**: [list files, or "(empty)"] **diplomas/**: [list files, or "(empty)"]
**references/**: [list files, or "(empty)"] **references/**: [list files, or "(empty)"]
**projects/**: [list files, or "(empty)"]
**applications/**: [list subfolders with their files, or "(empty)"] **applications/**: [list subfolders with their files, or "(empty)"]
I will read these and cross-reference before proposing any changes. I will read these and cross-reference before proposing any changes.
@@ -109,7 +110,7 @@ Hold this content in context throughout Path A. Do not re-read.
### Step A3: Parse Documents ### Step A3: Parse Documents
Read each document found in Step A1. Process subfolders in this order: `cv/`, `linkedin/`, `diplomas/`, `references/`, `applications/`. Read each document found in Step A1. Process subfolders in this order: `cv/`, `linkedin/`, `diplomas/`, `references/`, `projects/`, `applications/`.
**`cv/` documents:** name, contact (email, phone, LinkedIn, GitHub), education (degree, institution, dates, thesis), work experience (title, company, dates, location, bullets), skills, languages (with any stated proficiency), publications, awards, profile/summary. **`cv/` documents:** name, contact (email, phone, LinkedIn, GitHub), education (degree, institution, dates, thesis), work experience (title, company, dates, location, bullets), skills, languages (with any stated proficiency), publications, awards, profile/summary.
@@ -119,6 +120,8 @@ Read each document found in Step A1. Process subfolders in this order: `cv/`, `l
**`references/` documents:** referee name, title, organization; full text of the letter (extract specific quotes); competency language used. **`references/` documents:** referee name, title, organization; full text of the letter (extract specific quotes); competency language used.
**`projects/` documents:** project name, summary/description, problem domain, tech stack (languages, frameworks, tools), key technical challenges and architectural decisions, measurable outcomes/metrics (e.g. users, performance, stars, impact).
**`applications/<company>_<role>/` subfolders:** **`applications/<company>_<role>/` subfolders:**
- `job_posting.md`: role title, company, required skills, experience level, sector, role type - `job_posting.md`: role title, company, required skills, experience level, sector, role type
- `cover_letter.tex`: opening structure, body structure, bullet style, closing, recurring phrases - `cover_letter.tex`: opening structure, body structure, bullet style, closing, recurring phrases
@@ -157,12 +160,13 @@ If no inconsistencies, state "No cross-reference issues found." and continue.
For each skill file, compare extracted document content against the current file content from Step A2. Build two buckets. For each skill file, compare extracted document content against the current file content from Step A2. Build two buckets.
**Additive changes:** entirely new content not in the skill file in any form. Examples: a certification not in `01-candidate-profile.md`, a new endorsement skill, a referee not yet listed, a new behavioral quote from a reference letter, a new award. **Additive changes:** entirely new content not in the skill file in any form. Examples: a certification not in `01-candidate-profile.md`, a new independent project not in `01-candidate-profile.md`, a new endorsement skill, a referee not yet listed, a new behavioral quote from a reference letter, a new award.
**Conflicting changes:** content that touches something already in a skill file but disagrees. Examples: a different date range for an existing job, a different job title for the same role, a different graduation date than what is recorded. **Conflicting changes:** content that touches something already in a skill file but disagrees. Examples: a different date range for an existing job, a different job title for the same role, a different graduation date than what is recorded.
**Inference rules** (apply when populating from inferred sources): **Inference rules** (apply when populating from inferred sources):
- **`01-candidate-profile.md` (`## Independent Projects`):** Source is `projects/` documents. Extract structured project entries formatted as `- **[PROJECT_NAME]**: [DESCRIPTION with tech stack and measurable outcome]`. Ground all claims in the document text.
- **`02-behavioral-profile.md`:** Source is LinkedIn About + recommendation letters. Extract recurring themes, adjectives, phrases about how the candidate works. Add only to "Strongest Behavioral Traits", "How [Candidate] Works Best", or "Management Style Preferences" sections. Do not overwrite existing scored assessments. Always label inferred additions: *[Inferred from LinkedIn About / Reference letter - review before relying on this]* - **`02-behavioral-profile.md`:** Source is LinkedIn About + recommendation letters. Extract recurring themes, adjectives, phrases about how the candidate works. Add only to "Strongest Behavioral Traits", "How [Candidate] Works Best", or "Management Style Preferences" sections. Do not overwrite existing scored assessments. Always label inferred additions: *[Inferred from LinkedIn About / Reference letter - review before relying on this]*
- **`03-writing-style.md`:** Source is `cover_letter.tex` files. Extract recurring patterns. Add as observations under "## Patterns Observed in Past Applications". Do not modify existing rules. Only add if 2+ cover letters show a genuine pattern. - **`03-writing-style.md`:** Source is `cover_letter.tex` files. Extract recurring patterns. Add as observations under "## Patterns Observed in Past Applications". Do not modify existing rules. Only add if 2+ cover letters show a genuine pattern.
- **`04-job-evaluation.md`:** Source is `job_posting.md` + `outcome.md` pairs. If an application reached interview or offer: note role type and sector as a confirmed strong-fit signal. If 2+ applications repeat a no-response or rejection pattern: note it. Add findings under "## Calibration from Past Applications". Do not modify the existing scoring framework. - **`04-job-evaluation.md`:** Source is `job_posting.md` + `outcome.md` pairs. If an application reached interview or offer: note role type and sector as a confirmed strong-fit signal. If 2+ applications repeat a no-response or rejection pattern: note it. Add findings under "## Calibration from Past Applications". Do not modify the existing scoring framework.
@@ -193,6 +197,7 @@ Present the full change set before writing anything.
### 01-candidate-profile.md ### 01-candidate-profile.md
- [ ] New certification: [title], [issuer], [date] - extracted from LinkedIn - [ ] New certification: [title], [issuer], [date] - extracted from LinkedIn
- [ ] New independent project: [PROJECT_NAME] - [description, tech stack, key outcome]
- [ ] New reference: [name, title, company] - [ ] New reference: [name, title, company]
Quote: "[relevant quote]" Quote: "[relevant quote]"
+4
View File
@@ -12,8 +12,12 @@
"Bash(python3 salary_lookup.py:*)", "Bash(python3 salary_lookup.py:*)",
"Bash(python tools/rank_state.py:*)", "Bash(python tools/rank_state.py:*)",
"Bash(python3 tools/rank_state.py:*)", "Bash(python3 tools/rank_state.py:*)",
"Bash(python tools/job_key.py:*)",
"Bash(python3 tools/job_key.py:*)",
"Bash(python tools/verify_pdf.py:*)", "Bash(python tools/verify_pdf.py:*)",
"Bash(python3 tools/verify_pdf.py:*)", "Bash(python3 tools/verify_pdf.py:*)",
"Bash(python tools/verify_layout.py:*)",
"Bash(python3 tools/verify_layout.py:*)",
"Bash(pdftotext:*)" "Bash(pdftotext:*)"
] ]
} }
@@ -1,5 +1,5 @@
--- ---
framework_version: 1.4.3 framework_version: 1.4.4
--- ---
# CV Templates and Tailoring Guide # CV Templates and Tailoring Guide
@@ -42,6 +42,13 @@ Expected output: `Output written on main_<company>_<role>.pdf (2 pages, ...)`. A
\renewcommand*{\sectionstyle}[1]{{\sectionfont\color{color1}#1}} \renewcommand*{\sectionstyle}[1]{{\sectionfont\color{color1}#1}}
\usepackage[utf8]{inputenc} \usepackage[utf8]{inputenc}
% pdflatex fallback only (the documented engine is lualatex, which skips this
% branch). Without T1 font encoding pdflatex builds accented letters with
% \accent, and the PDF text layer stores them decomposed - `e` + U+0300 rather
% than U+00E8 - so an ATS keyword match on "Genève" fails while the page looks
% right. moderncv 2.5 loads T1 itself under pdflatex; 2.3.1 (Debian/Ubuntu apt)
% does not. \ifpdftex comes from iftex, which every moderncv version loads.
\ifpdftex\usepackage[T1]{fontenc}\fi
% moderncv loads hyperref itself in an \AtEndPreamble hook, so \hypersetup % moderncv loads hyperref itself in an \AtEndPreamble hook, so \hypersetup
% must go in an \AtEndPreamble of our own: on moderncv < 2.4 a top-level % must go in an \AtEndPreamble of our own: on moderncv < 2.4 a top-level
% \usepackage{hyperref} clashes with the class's own % \usepackage{hyperref} clashes with the class's own
@@ -277,7 +284,8 @@ What to check in the extraction:
- **Contact details as literal text.** The stock template's fontawesome contact icons extract as glyph names (`MOBILE-ALT`, `Envelope`) - harmless noise, because the actual address and number are printed beside them. The failure mode is a contact detail carried *only* by an icon or a hyperlink (like the `LinkedIn` link text, whose URL is not in the text layer): invisible to an ATS. The email address must always appear as printed text. - **Contact details as literal text.** The stock template's fontawesome contact icons extract as glyph names (`MOBILE-ALT`, `Envelope`) - harmless noise, because the actual address and number are printed beside them. The failure mode is a contact detail carried *only* by an icon or a hyperlink (like the `LinkedIn` link text, whose URL is not in the text layer): invisible to an ATS. The email address must always appear as printed text.
- **No garbled output.** `(cid:NNN)` markers or `` characters mean a font is embedded without a Unicode mapping - an ATS sees the same garbage. This shows up with unusual fonts in custom templates, not with the stock moderncv setup under lualatex. - **No garbled output.** `(cid:NNN)` markers or `` characters mean a font is embedded without a Unicode mapping - an ATS sees the same garbage. This shows up with unusual fonts in custom templates, not with the stock moderncv setup under lualatex.
- **Reading order.** The stock banking style is single-column, so extraction order matches visual order. Custom templates (via `/add-template`) with sidebars or multi-column layouts can interleave unrelated lines; if extraction order is scrambled, the user is trading ATS compatibility for looks and should be told. - **Reading order.** The stock banking style is single-column, so extraction order matches visual order. Custom templates (via `/add-template`) with sidebars or multi-column layouts can interleave unrelated lines; if extraction order is scrambled, the user is trading ATS compatibility for looks and should be told.
- **Keyword coverage.** Match the posting's required/preferred terms against the extracted text, in the posting's language. Prefer the posting's exact term over a synonym when it is truthfully applicable - ATS matching is often literal. Never add a keyword the profile does not support. - **Keyword coverage.** Match the posting's required/preferred terms against the extracted text, in the posting's language. Prefer the posting's exact term over a synonym when it is truthfully applicable - ATS matching is often literal. Never add a keyword the profile does not support. `verify_pdf.py --contains` folds both sides for whitespace, Unicode normalization (NFC) and LaTeX's typographic substitutions before comparing - `'` reaches the text layer as U+2019 and `--` as U+2013, so `--contains "Master's degree"` and `--contains "2016-2024"` match what the template actually renders. The dumped `.txt` is never folded: it is the raw layer the ATS sees, which is why the date-range check below reads the dump, not `--contains`.
- **Accents intact (pdflatex fallback).** Under pdflatex without T1 font encoding the text layer stores accented letters decomposed (`e` + combining grave instead of `è`); pypdf reads that as `Gen` `eve` with a stray spacing accent, and neither form matches a typed keyword. The stock template guards this with `\ifpdftex\usepackage[T1]{fontenc}\fi`; keep the line in tailored CVs and custom templates that may be compiled with pdflatex. It is a no-op under lualatex.
### Date fields must be ASCII ranges (confirmed ATS import failure) ### Date fields must be ASCII ranges (confirmed ATS import failure)
@@ -1,5 +1,5 @@
--- ---
framework_version: 1.1.0 framework_version: 1.1.1
--- ---
# Web Research and Fetching # Web Research and Fetching
@@ -48,7 +48,7 @@ Two details worth knowing, both covered by `tests/test_robots_check.py`:
### The retry: curl with browser headers ### The retry: curl with browser headers
```bash ```bash
cd "$SCRATCHPAD" && curl -sSL --max-time 45 -o page.html -w "HTTP %{http_code} size=%{size_download}\n" \ cd "${SCRATCHPAD:?set this to the session scratchpad directory from your system prompt}" && curl -sSL --max-time 45 -o page.html -w "HTTP %{http_code} size=%{size_download}\n" \
-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36' \ -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' \ -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' \
-H 'Accept-Language: en-GB,en;q=0.9' \ -H 'Accept-Language: en-GB,en;q=0.9' \
@@ -65,7 +65,7 @@ Write to the session scratchpad directory, never into the repo. `--compressed` i
`WebFetch` converts to markdown for you; curl does not. Strip the tags: `WebFetch` converts to markdown for you; curl does not. Strip the tags:
```bash ```bash
cd "$SCRATCHPAD" && python3 -c " cd "${SCRATCHPAD:?set this to the session scratchpad directory from your system prompt}" && python3 -c "
import re, html import re, html
h = open('page.html', encoding='utf-8', errors='replace').read() h = open('page.html', encoding='utf-8', errors='replace').read()
h = re.sub(r'(?is)<(script|style|noscript|svg)[^>]*>.*?</\1>', ' ', h) h = re.sub(r'(?is)<(script|style|noscript|svg)[^>]*>.*?</\1>', ' ', h)
+17 -5
View File
@@ -5,7 +5,7 @@ description: >
(LinkedIn, local job boards, and any skills added with /add-portal). Deduplicates (LinkedIn, local job boards, and any skills added with /add-portal). Deduplicates
across runs. Triggers on: job scrape, find jobs, search jobs, new jobs, job search, across runs. Triggers on: job scrape, find jobs, search jobs, new jobs, job search,
scrape jobs, /scrape scrape jobs, /scrape
allowed-tools: Read, Write, Edit, Glob, Grep, Bash(bun --version), Bash(bun run .agents/skills/*/cli/src/cli.ts *), WebFetch, WebSearch, Agent, AskUserQuestion allowed-tools: Read, Write, Edit, Glob, Grep, Bash(bun --version), Bash(bun run .agents/skills/*/cli/src/cli.ts *), Bash(python tools/job_key.py:*), Bash(python3 tools/job_key.py:*), WebFetch, WebSearch, Agent, AskUserQuestion
--- ---
# Job Scraper # Job Scraper
@@ -117,7 +117,10 @@ site for the role and store that URL instead, or drop the candidate rather than
fragment link. fragment link.
For every candidate: For every candidate:
- Skip if the URL or company+title combo already exists in `seen_jobs.json` - Skip if the URL matches any existing `seen_jobs.json` entry, regardless of
that entry's key. This preserves dedup continuity for postings stored under
the pre-helper key rule while new entries use the canonical key from Step 4.
- Otherwise, skip if the company+title combo already exists in `seen_jobs.json`
- Skip if the company+role already appears in `job_search_tracker.csv` - Skip if the company+role already appears in `job_search_tracker.csv`
### Step 2.5: Mass-Posting Detection (within this run) ### Step 2.5: Mass-Posting Detection (within this run)
@@ -138,11 +141,19 @@ For each new job, do a rapid fit check (NOT the full evaluation from `04-job-eva
### Step 4: Deduplicate & Store ### Step 4: Deduplicate & Store
1. Add ALL fetched jobs (new and skipped) to `seen_jobs.json` with structure: 1. Derive each entry's key with the helper, never by slugifying in the moment:
```bash
python3 tools/job_key.py --company "<company>" --title "<title>" --url "<url>"
```
It prints one line: the canonical key for that posting. The key must be a pure function of the posting, because two runs that slugify differently store the same job twice and defeat the dedup this step exists to provide. The helper also length-caps long titles and disambiguates the cap with a hash of the full slug, so a truncated title is stable across runs and two different long titles never collide. `python3 tools/job_key.py --audit` reports entries in an existing state file that predate this rule; it only reports, and never rewrites keys, since a rewritten key breaks the tracker's own company+role matching.
2. Add ALL fetched jobs (new and skipped) to `seen_jobs.json` with structure:
```json ```json
{ {
"seen": { "seen": {
"<url_or_company_title_key>": { "<key from tools/job_key.py>": {
"title": "...", "title": "...",
"company": "...", "company": "...",
"url": "...", "url": "...",
@@ -168,7 +179,8 @@ The `source` field records which mechanism produced the entry: `cli` for Step 1b
`posted_date` is the posting's own publication date, taken from the `date` field Step 2's contract already guarantees on every portal CLI's search output. Step 1b uses that date to scope the run to the last 14 days and then drops it, so nothing downstream can distinguish a posting published yesterday from one published two years ago - `first_seen` is when this scraper first saw the entry, not when the employer posted it. Persisting it makes Step 1b's window auditable after the run and gives `/rank` a freshness signal to weigh, instead of rediscovering the date and recording it in prose that nothing reads. That gap landed for real: a freehire-search posting dated 2024-05-13 was scraped and ranked Strong Fit at position 1 of 133, its own scoring note observing the listing "may be long stale" with nothing able to act on it. `null` means the portal returned no date for that result (the CLIs emit `date: null` when a listing omits it); a missing key means the entry predates this field - **never infer a posting date** from either, and never backfill by guessing. `posted_date` is the posting's own publication date, taken from the `date` field Step 2's contract already guarantees on every portal CLI's search output. Step 1b uses that date to scope the run to the last 14 days and then drops it, so nothing downstream can distinguish a posting published yesterday from one published two years ago - `first_seen` is when this scraper first saw the entry, not when the employer posted it. Persisting it makes Step 1b's window auditable after the run and gives `/rank` a freshness signal to weigh, instead of rediscovering the date and recording it in prose that nothing reads. That gap landed for real: a freehire-search posting dated 2024-05-13 was scraped and ranked Strong Fit at position 1 of 133, its own scoring note observing the listing "may be long stale" with nothing able to act on it. `null` means the portal returned no date for that result (the CLIs emit `date: null` when a listing omits it); a missing key means the entry predates this field - **never infer a posting date** from either, and never backfill by guessing.
2. Only present jobs NOT already in the seen list or tracker. 3. Only present jobs NOT already in the seen list (matched by URL or
company+title) or tracker.
### Step 4.5: Generate Referral Contact Links (High & Medium Fit Only) ### Step 4.5: Generate Referral Contact Links (High & Medium Fit Only)
+1
View File
@@ -73,6 +73,7 @@ documents/cv/**
documents/linkedin/** documents/linkedin/**
documents/diplomas/** documents/diplomas/**
documents/references/** documents/references/**
documents/projects/**
# Also where /interview saves its prep packs (interview_prep_<stage>.md): these # Also where /interview saves its prep packs (interview_prep_<stage>.md): these
# name the employers applied to, quote what was submitted, and set out the # name the employers applied to, quote what was submitted, and set out the
# candidate's weak points. # candidate's weak points.
+245
View File
@@ -13,6 +13,251 @@ per-file diff commands.
## [Unreleased] ## [Unreleased]
### Added
- **`documents/projects/` portfolio ingestion in `/setup` (Path A)** (`documents/README.md`,
`.claude/commands/setup.md`, `.claude/commands/reset.md`, `tests/test_setup_command.py`) -
onboards project writeups, case studies, and documentation (`.md`, `.txt`, `.pdf`)
from `documents/projects/`, extracting structured summaries (problem domain, tech stack,
technical challenges, and measurable outcomes) to populate `## Independent Projects`
in `01-candidate-profile.md`.
- **Source host verification in `/apply` Step 1** (#431, `.claude/commands/apply.md`,
`tests/test_apply_host_check.py`) - before proceeding to draft CV and cover letters,
Step 1 verifies the posting URL's provenance against installed portal boards and the
six standard ATS apex domains (`greenhouse.io`, `lever.co`, `myworkdayjobs.com`/`workday.com`,
`ashbyhq.com`, `smartrecruiters.com`, `workable.com`). Look-alike prefix/suffix spoofing
fails closed, and unrecognized hosts are plainly flagged as unverified in the evaluation
output (`⚠ Unverified source host: <hostname>`) before drafting tokens are spent.
- **`/expand` project and portfolio expansion** (`.claude/commands/expand.md`,
`tests/test_expand_command.py`) - expands candidate discovery
to technical projects from public GitHub repositories, extracting structured summaries
(problem domain, tech stack, key technical challenges, and verifiable outcomes) to
populate the `## Independent Projects` section of `01-candidate-profile.md`.
- **Stale sweep branch in `/outcome`** (`.claude/commands/outcome.md`,
`tests/test_outcome_stale.py`) - introduces `/outcome stale [N]` (and `/outcome sweep [N]`)
to batch-resolve open applications quiet for 60+ (or N) days. Displays a numbered summary
of qualifying applications, requires explicit user confirmation (`all`, `select`, or `skip`),
resolves confirmed rows to `no_response`, logs dated entries to `notes`, updates archive
`outcome.md` files, and hands off to calibration when 3+ applications are resolved.
- **Mechanical layout verification for compiled PDFs** - `tools/verify_layout.py` measures
what `/apply` Step 5b previously only eyeballed: per-page text extent, bottom whitespace,
the largest internal vertical gap, footer collisions, and entry headers or section
headings stranded at a page break. It exists for a failure that survives every existing
check - a moderncv `\cventry` is an unbreakable `tabular`, so an entry that does not fit
jumps to the next page and leaves a hole behind (observed at 273pt, roughly 19 blank
lines) while the document still compiles, still reports the correct page count, and still
passes `tools/verify_pdf.py`. Geometry comes from Poppler `pdftotext -bbox`; Poppler is
optional repo-wide (since #369 `verify_pdf.py` prefers pypdf), and word bounding boxes
have no pypdf equivalent, so this is the one step that still wants it. A missing Poppler
- or the xpdf-based `pdftotext` Git for Windows puts ahead of it in PATH, which rejects
`-bbox` - degrades to a `skipped:` exit 2 rather than reporting a phantom layout failure.
Page count is deliberately left to `verify_pdf.py --pages` so that one rule keeps one
implementation. Thresholds are calibrated for the stock moderncv and `cover.cls`
geometry. Tests use synthetic page geometry, so they need neither Poppler nor a
LaTeX toolchain.
### Fixed
- **`/apply` Step 5b now actually runs the page-count check it claimed Step 5d ran**
(`.claude/commands/apply.md`, `tests/test_apply_page_count.py`) - the 5b prose said
"Page count is not checked here - that is `verify_pdf.py --pages`'s job, and Step 5d already
runs it", and `verify_layout.py`'s docstring declines to measure page count for the same
reason. Step 5d's only `verify_pdf.py` call is `--dump-text`, and no step in the workflow
passed `--pages` at all (only the upstream-only CI assertion on the stock examples does),
so the hard 2-page CV and 1-page cover letter limits were enforced by nothing but the
visual PDF read - the "measure first, then look" failure 5b was written to stop. 5b now
runs `verify_pdf.py --pages 2` on the CV and `--pages 1` on the cover letter ahead of
`verify_layout.py`, names the `ACTIVE-TEMPLATE` page limit as the substitute for a custom
template, and the deferral sentence points at those lines. Four spec tests pin the
invocations, their counts, their order relative to the layout measurement, and that no
prose defers the check to a step that does not run it; all four fail on master.
- **`salary_lookup.py` prints the privacy footnote only when a row actually carries `N/A*`**
- the `* N/A = Too few employees to publish (privacy)` line was appended under every
category table, including one where every row has an index, so the output asserted a
suppression that never happened (the residual noted on #470). The footnote now follows a
flag set by the `N/A*` branch; a table with a suppressed row renders exactly as before.
Two `FormatEntryTests` cases pin both directions; the "omitted" one fails on master.
- **`convert_salary_excel.py` pairs a bare `Count`/`Index` column pair instead of
splitting it, so `salary_lookup.py` no longer labels a published headcount as
privacy-suppressed** - the pairing loop required a non-empty derived category name on
both sides, but a header with no category word (`Count` + `Index`, Danish `Antal` +
`Lønindeks`) strips to an empty name, so the simplest layout the README advertises
("auto-pairs count/index columns") came out as two unrelated standalone categories:
`{"count": {"count": 500}, "index": {"index": 108.5}}`. `salary_lookup` then rendered
a `Count 500 N/A*` row above an `Index - 108.5` row, and the footnote read the
`N/A*` as "too few employees to publish (privacy)" - a false statement about a company
whose headcount is in the file, shown during `/apply`'s salary step. Demonstrated
through the documented Excel -> JSON -> lookup path with `openpyxl`; adding any suffix
(`Antal alle`) made pairing work, which is why the shipped tests, all suffixed, never
saw it. Bare pairs now pair under the README's top-level category name
(`all_employees`); a bare `Antal` with no bare index column still stays a standalone
count, and named pairs alongside are untouched. Four new cases in
`test_convert_salary_excel.py`, including one that renders the converter's output
through `salary_lookup.format_entry`; all four fail on the old pairing rule.
- **`tools/verify_layout.py`'s `skipped:` message named only one cause of a broken
extractor when there are two** (#451) - it blamed the xpdf-based `pdftotext` Git for
Windows puts ahead of Poppler in PATH (no `-bbox` flag, exits 99), but a real Poppler
can abort `-bbox`/`-bbox-layout`/`-htmlmeta` too: Poppler 26.0x before 26.05 crashes on
any PDF whose Info dictionary carries an empty string in any field, and `hyperref`
writes exactly that for every field it does not set. A `lualatex`/`pdflatex` document
built with `hyperref` and no `\hypersetup{pdftitle=...}` - an ordinary `/add-template`
CV template, not a malformed one - hits this with a working Poppler installed, and the
old message sent the reader to check their PATH when nothing was wrong with it. The
message now names both causes; behavior is unchanged, degrading to `skipped:` exit 2
either way, since a broken extractor is still not a broken document.
- **The template-placeholder guard in `test_setup_command.py` now skips on forks** (#463) -
`TemplatesStillCarryThePlaceholders` asserts that `05-cv-templates.md` and
`06-cover-letter-templates.md` still contain `[FIRST_NAME]`, `[LAST_NAME]`, `[YOUR_EMAIL]`,
`[YOUR_PHONE]`, `[YOUR_NAME]`, and `[YOUR_LINKEDIN_URL]`. Running `/setup` - the documented
path, and what Step 3.5/3.6 of that command exist to do - replaces exactly those tokens, so on
a personalized fork `python3 -m unittest discover -s tests` fails both checks permanently and
marks every push red. The class now uses the same `@unittest.skipIf` on `GITHUB_REPOSITORY`
(defaulting to upstream when unset, so local pristine-template runs still execute the guards)
that `test_placeholder_integrity.py` received in #407. The guard landed three days after that
fix and did not pick up the pattern; the `placeholder-integrity` CI job is upstream-gated and
does not cover the `05`/`06` tokens, so `python-tests` was their only check.
- **`verify_pdf.py --contains` now sees through LaTeX's typographic substitutions and
the pdflatex text layer keeps accents precomposed** (Discussions #385, #384) - the
comparison folded whitespace only, but LaTeX ligatures `'` into U+2019 and `--` into
U+2013, so on the stock CV compiled with the documented `lualatex` command
`--contains "Master's degree"` and `--contains "2016-2024"` both reported the keyword
missing from a document that plainly contains it (measured through both extractors;
`Six Sigma` and `Statistics` on the same page passed). The documented remedy for a
missing keyword is to add it, so the false negative nudged toward the one thing the ATS
section forbids. `normalize_text()` now folds both sides - NFC, then curly
apostrophes/quotes to ASCII, en/em dashes to `-`, no-break space to space - at
comparison time only; `--dump-text` still writes the raw layer, because that is what an
ATS parses and the date-range rule in `05-cv-templates.md` needs the raw en-dash visible
there. Separately, pdflatex without T1 font encoding stores accents decomposed
(`e` + U+0300; pypdf reads it as a stray spacing accent), which NFC cannot fully
repair - moderncv 2.5 loads T1 itself under pdflatex but the apt-packaged 2.3.1 does
not, so `cv/main_example.tex` and the guide's preamble gain
`\ifpdftex\usepackage[T1]{fontenc}\fi`, a no-op on the lualatex path. Pinned by
ten new `test_verify_pdf.py` cases (the fold-through ones fail on the whitespace-only
code) and a `test_latex_guidance.py` guard that the line exists and stays
pdflatex-only. Reported and diagnosed by 9scorp4. Fork users: your
personalized `cv/main_example.tex` gains the one guarded preamble line on rebase (a clean
3-way merge unless you edited the preamble); tailored CVs compiled with lualatex need nothing.
- **`jobdanmark-search detail` now backs off on 429/5xx like every other portal's detail
command** - the handler called `fetch()` directly instead of going through the CLI's own
request wrappers, so it carried none of the three things `apiFetch`/`apiPost` guarantee:
no 429/5xx retry loop (a rate-limited detail page wrote `API_ERROR` and exited after one
attempt, where jobnet, jobbank, jobindex, linkedin, and freehire all retry up to six
times), a hand-inlined User-Agent string that would drift from the exported `USER_AGENT`,
and a timeout the wrappers' tests never saw. `/scrape` calls `detail` once per
shortlisted posting, so a burst that tripped jobdanmark's rate limiter dropped those
postings outright - no description, no deadline - while the same burst on any other
portal rode it out. Demonstrated by driving the real command handler with a stubbed 429:
1 fetch attempt and exit 1 before, 7 attempts after (the contract's initial try plus six
retries). Fixed by adding `htmlFetch` to `helpers.ts` with the same backoff schedule,
timeout, and shared User-Agent as the JSON wrappers (404 returns `null` so `detail` keeps
its `NOT_FOUND` contract) and routing `detail` through it. Pinned in the existing
`retry-backoff`, `user-agent`, and `request-timeout` suites, which now cover all three
wrappers, plus a new `detail-backoff.test.ts` that exercises the handler path itself -
its retry cases fail against the bare `fetch()`.
- **Free-form tracker notes no longer break the CSV row** (#454) (`.claude/commands/gmail-sync.md`,
`.claude/commands/outcome.md`, `tests/test_tracker_notes_csv_safe.py`) - two writers put
free-form text into the `notes` column of `job_search_tracker.csv`: `/gmail-sync` Step 7a
copied the raw subject of a received email, and `/outcome` Step 4 appended "a short dated
note" with no constraint on its content. No writer in the framework emits a quoted tracker
field, so an unescaped comma splits the row for a naive split and for `csv.DictReader` alike -
the latter being what the repo's only machine reader of the tracker uses
(`tools/rank_state.py`). `notes` is column 10 of 14, so a subject as ordinary as
`Re: Your application, Data Scientist`, or a note as natural as `rejected, no feedback given`,
shifted `cv_file`, `cover_letter_file` and `source` a column left. A line break is worse: it
ends the row and starts a second one. Nothing validated the row afterwards, and the
`/gmail-sync` half was written unattended, so the corruption was silent. Both append
instructions now carry the rule themselves - `/gmail-sync` deletes commas, double quotes and
line breaks from the subject, `/outcome` writes its note without them - rather than a general
note a writer can miss. Nothing is lost on the `/gmail-sync` side: Step 7a item 2 still
records the subject verbatim in the archive's `outcome.md`, which is Markdown and carries no
such constraint. The fixed-format writers (`followed up YYYY-MM-DD`,
`stale resolved no_response (YYYY-MM-DD)`, `redrafted`) could never contain these characters
and are unchanged.
- **`jobindex-search detail` no longer fetches arbitrary URLs or invents posting-shaped
output** (#447) - the command fetched any `http(s)` input verbatim (no host check) and,
when the path didn't match its one pattern, silently used the whole input URL as the job
id; the only net was "the fetched page has a title", so a non-posting page came back as
a well-formed fake posting with exit 0 (demonstrated with jobindex's own homepage:
`id` = the URL, `title` = the site's tagline, `description` = navigation chrome). Every
other portal CLI rejects unparseable detail input with `BAD_ID` and constructs its fetch
URL from the extracted id; jobindex was the one CLI trusting the raw string - and
`/scrape`/`/rank` agents feed it stored URLs, so a ghost or redirected URL (the #331
class) yielded plausible garbage instead of an error. `buildUrl` now requires a
jobindex.dk host (apex or subdomain - look-alike and userinfo tricks rejected via real
URL parsing) plus a `/jobannonce/<id>` path, rebuilds the fetch URL from the extracted
id (the canonical short form the bare-id path always used), and exits 1 with the
stderr-JSON `BAD_ID` contract otherwise; bare ids stay permissive scheme- and
slash-free tokens (the jobnet precedent - the server 404s unknowns loudly). Pinned by
eight cases in the new `detail-input.test.ts`; the five rejection/canonicalization
cases fail against the verbatim unguarded extraction. Complementary to the `/apply`
host-check rule proposed in #431, which stays with its proposer.
- **`/outcome` and `/interview` no longer confuse two roles at the same company** (#443)
(`.claude/commands/outcome.md`, `.claude/commands/interview.md`,
`tests/test_apply_records_application.py`) - when a tracker row's `cv_file` /
`cover_letter_file` columns are empty, both commands fell back to a company-prefix glob
(`cv/main_<company>*.tex`). Two roles at one company both match it, so `/outcome` copied
whichever the filesystem returned first into the archive as `cv_draft.tex` - the file whose
purpose is to record what was actually submitted - and its own "leave an existing archived
file" rule then made the wrong copy permanent. Both fallbacks now glob the full
`<company>_<role>` stem, derived by the **Subfolder naming** rule in `documents/README.md`
rather than restated, and skip with a note instead of widening the search. Dropping the
hardcoded `.tex` also makes a template registered by `/add-template` findable.
- **`jobnet-search detail` no longer reports an externally hosted ad as not found** (#432) -
Jobnet's `/FindJob/JobAdDetails/<id>` returns 404 for ads with `isExternal: true`, so `detail`
on an ad `search` had just listed exited 1 with `NOT_FOUND`, and `/scrape` read the posting as
gone rather than hosted elsewhere (2 of 3 ads in a fresh sample). On that 404 the command now
falls back to the search endpoint, which does carry the ad's description and the external
application URL, and returns the record marked `isExternal: true` with a stderr note; fields the
search payload does not carry (`views`, `approvalStatus`, the boolean flags) are `null`, never
guessed. Verified live on two external ads.
- **`09-web-research.md`'s curl snippets no longer write into the repo when `$SCRATCHPAD`
is unset** - both runnable blocks in the 403-escalation path start with `cd "$SCRATCHPAD"`,
and nothing in the repository ever sets that variable (`git grep 'SCRATCHPAD='` returns
nothing). Unset, it expands to `cd ""`, which succeeds and leaves the shell where it
started, so the `&&` chain proceeds and `curl -o page.html` writes to the working
directory - in practice the checkout, which is exactly what the paragraph directly beneath
the curl block forbids ("Write to the session scratchpad directory, never into the repo").
The file's instruction and its own snippet disagreed, and the snippet won silently.
Both expansions are now guarded with `${SCRATCHPAD:?...}`, turning a silent repo write into
an immediate failure whose message names where the value comes from. Behaviour is unchanged
wherever the variable is set. The same undefined reference in `.claude/commands/rank.md`
was removed by #425 as a side effect of rewriting Step 2/4; this is the remaining instance.
- **`seen_jobs.json` keys are now a pure function of the posting** - `/scrape` Step 4 described
the key as prose (`"<url_or_company_title_key>"`) and nothing said how to derive it, so each
run slugified in its own way. Two failures followed, both observed in a live state file. Keys
carried characters that break the path they later become: `/apply` and `/outcome` derive an
archive folder from the same company+role pair, which is why `documents/README.md` has a
subfolder rule, and keys like `deloitte_junior-cybersecurity-analyst-(ot/iot)` and
`neverhack-estonia_penetration-tester-/-red-teamer` violate it. And the same posting was
stored twice when two runs truncated one title at different points
(`deloitte_cyber-intelligence-center-security-analy` and
`...-security-analyst-at` are one job, one URL, two entries) - which defeats the dedup the
file exists for. `tools/job_key.py` now owns the derivation: the slug is normalised, and
truncation is length-capped *and* disambiguated by a hash of the full slug, so a long title
always produces the same key and two long titles sharing a prefix cannot collide. Step 4
calls the helper instead of describing it. `--audit` reports non-conforming entries in an
existing state file and deliberately never rewrites them: stored keys are matched against
`job_search_tracker.csv` by company+role elsewhere, so a silent rewrite would break the link
between a stored job and its application record.
Existing state files need no migration: Step 2's candidate filter matches a posting to a stored
entry by URL regardless of that entry's key, so a workspace whose entries predate the helper does
not see its still-live postings re-presented as new.
## [1.7.1] - 2026-09-06 ## [1.7.1] - 2026-09-06
### Added ### Added
+2 -1
View File
@@ -61,7 +61,7 @@ The framework encodes career guidance best practices, including structured evalu
## Prerequisites ## Prerequisites
- [Claude Code](https://claude.com/claude-code) (CLI). Using a different agent tool (Codex, Antigravity, Gemini CLI)? Start at [`AGENTS.md`](AGENTS.md) - the portal search skills work there out of the box, and [community forks](https://github.com/MadsLorentzen/ai-job-search/discussions/78) adapt the full workflow. - [Claude Code](https://claude.com/claude-code) (CLI). Claude Code has no free tier: you need a Claude Pro/Max/Team subscription or Anthropic API credits (pay-per-token, usually cheaper for occasional use). Using a different agent tool (Codex, Antigravity, Gemini CLI)? Start at [`AGENTS.md`](AGENTS.md) - the portal search skills work there out of the box, and [community forks](https://github.com/MadsLorentzen/ai-job-search/discussions/78) adapt the full workflow.
- Python 3.10+ - Python 3.10+
- [Bun](https://bun.sh) (for job search CLI tools) - [Bun](https://bun.sh) (for job search CLI tools)
- LaTeX distribution with `lualatex` and `xelatex`: [TeX Live](https://tug.org/texlive/), [MacTeX](https://tug.org/mactex/), [TinyTeX](https://yihui.org/tinytex/), or [MiKTeX](https://miktex.org/). The CV compiles with `lualatex` (pdflatex often fails on modern MiKTeX installs with `fontawesome5` font-expansion errors); the cover letter compiles with `xelatex` because `cover.cls` requires `fontspec`. If using a minimal TeX install such as TinyTeX or BasicTeX, install the extra packages listed in [SETUP.md](SETUP.md#minimal-tex-install-tinytexbasictex). - LaTeX distribution with `lualatex` and `xelatex`: [TeX Live](https://tug.org/texlive/), [MacTeX](https://tug.org/mactex/), [TinyTeX](https://yihui.org/tinytex/), or [MiKTeX](https://miktex.org/). The CV compiles with `lualatex` (pdflatex often fails on modern MiKTeX installs with `fontawesome5` font-expansion errors); the cover letter compiles with `xelatex` because `cover.cls` requires `fontspec`. If using a minimal TeX install such as TinyTeX or BasicTeX, install the extra packages listed in [SETUP.md](SETUP.md#minimal-tex-install-tinytexbasictex).
@@ -225,6 +225,7 @@ ai-job-search/
│ ├── robots_check.py # Gate the browser-header retry against robots.txt │ ├── robots_check.py # Gate the browser-header retry against robots.txt
│ ├── security_guards.py # CI guards: permission allowlist, gitignore rules, manifests │ ├── security_guards.py # CI guards: permission allowlist, gitignore rules, manifests
│ ├── upstream_triage.py # Sort upstream commits into worth-reviewing vs probably-skip │ ├── upstream_triage.py # Sort upstream commits into worth-reviewing vs probably-skip
│ ├── verify_layout.py # Measure a compiled PDF's page layout (holes, orphans, footer collisions)
│ ├── verify_pdf.py # Verify a compiled PDF's page count and extractable text │ ├── verify_pdf.py # Verify a compiled PDF's page count and extractable text
│ └── README_SALARY_TOOL.md # Salary tool setup instructions │ └── README_SALARY_TOOL.md # Salary tool setup instructions
├── job_scraper/ # Scraper state (seen jobs, results) ├── job_scraper/ # Scraper state (seen jobs, results)
+7
View File
@@ -23,6 +23,13 @@
\renewcommand*{\sectionstyle}[1]{{\sectionfont\color{color1}#1}} \renewcommand*{\sectionstyle}[1]{{\sectionfont\color{color1}#1}}
\usepackage[utf8]{inputenc} \usepackage[utf8]{inputenc}
% pdflatex fallback only (the documented engine is lualatex, which skips this
% branch). Without T1 font encoding pdflatex builds accented letters with
% \accent, and the PDF text layer stores them decomposed - `e` + U+0300 rather
% than U+00E8 - so an ATS keyword match on "Genève" fails while the page looks
% right. moderncv 2.5 loads T1 itself under pdflatex; 2.3.1 (Debian/Ubuntu apt)
% does not. \ifpdftex comes from iftex, which every moderncv version loads.
\ifpdftex\usepackage[T1]{fontenc}\fi
% moderncv loads hyperref itself in an \AtEndPreamble hook, so \hypersetup % moderncv loads hyperref itself in an \AtEndPreamble hook, so \hypersetup
% must go in an \AtEndPreamble of our own: on moderncv < 2.4 a top-level % must go in an \AtEndPreamble of our own: on moderncv < 2.4 a top-level
% \usepackage{hyperref} clashes with the class's own % \usepackage{hyperref} clashes with the class's own
+20
View File
@@ -12,6 +12,7 @@ documents/
├── linkedin/ # LinkedIn profile export (PDF) ├── linkedin/ # LinkedIn profile export (PDF)
├── diplomas/ # Degree certificates and transcripts ├── diplomas/ # Degree certificates and transcripts
├── references/ # Reference letters ├── references/ # Reference letters
├── projects/ # Independent project summaries, case studies, or portfolio docs
├── postings/ # Raw job posting text, pasted manually for pages Claude can't fetch ├── postings/ # Raw job posting text, pasted manually for pages Claude can't fetch
│ └── <Company> - <Job Title>.txt # Filename = company + job title, content = full posting text │ └── <Company> - <Job Title>.txt # Filename = company + job title, content = full posting text
├── applications/ # Past job applications ├── applications/ # Past job applications
@@ -97,6 +98,25 @@ Reference letters from former managers, supervisors, or collaborators.
--- ---
## projects/
Summaries, case studies, READMEs, writeups, or documentation for independent, open-source, freelance, or personal portfolio projects.
**Supported formats:** `.md`, `.txt`, `.pdf`
**What `/setup` extracts:**
- Project name and description
- Problem domain and target audience
- Tech stack, tools, and libraries used
- Key technical challenges and architectural decisions
- Measurable outcomes, metrics, or performance improvements (added to `01-candidate-profile.md` under `## Independent Projects`)
**Naming:** Use descriptive project names, e.g. `project_realtime_chat.md`, `portfolio_compiler.txt`, `open_source_etl.pdf`.
**Tip:** These feed into the `## Independent Projects` section of `01-candidate-profile.md` and provide concrete technical evidence that `/apply` can weave into tailored CVs and cover letters.
---
## postings/ ## postings/
A drop folder for raw job posting text when Claude can't fetch a page directly (bot-blocked ATS platforms like Lever, Greenhouse behind Cloudflare, JS-heavy SPAs that return empty content, etc.). You open the posting yourself and paste the full text into a `.txt` file here. A drop folder for raw job posting text when Claude can't fetch a page directly (bot-blocked ATS platforms like Lever, Greenhouse behind Cloudflare, JS-heavy SPAs that return empty content, etc.). You open the posting yourself and paste the full text into a `.txt` file here.
View File
+7 -1
View File
@@ -319,6 +319,7 @@ def format_entry(entry, metadata):
lines.append(f" {'Category':<22} {'Count':>6} {index_label:>8} {'vs Baseline':>10}") lines.append(f" {'Category':<22} {'Count':>6} {index_label:>8} {'vs Baseline':>10}")
lines.append(f" {'-'*50}") lines.append(f" {'-'*50}")
suppressed = False # did any row render its index as N/A*?
for label, data in categories.items(): for label, data in categories.items():
display_label = label.replace("_", " ").title() display_label = label.replace("_", " ").title()
count = data.get("count") count = data.get("count")
@@ -339,9 +340,14 @@ def format_entry(entry, metadata):
else: else:
index_str = "N/A*" index_str = "N/A*"
diff_str = "" diff_str = ""
suppressed = True
lines.append(f" {display_label:<22} {count_str:>6} {index_str:>8} {diff_str:>10}") lines.append(f" {display_label:<22} {count_str:>6} {index_str:>8} {diff_str:>10}")
lines.append(f"\n * N/A = Too few employees to publish (privacy)") # The footnote explains the N/A* marker; printing it under a table with
# no such row asserts a privacy suppression that did not happen.
lines.append("")
if suppressed:
lines.append(" * N/A = Too few employees to publish (privacy)")
if metadata.get("baseline_description"): if metadata.get("baseline_description"):
lines.append(f" {metadata['baseline_description']}") lines.append(f" {metadata['baseline_description']}")
else: else:
+131
View File
@@ -0,0 +1,131 @@
"""Guards for /apply's source host verification rule in Step 1 (#431).
Pins the invariants from the maintainer design in issue #431:
- URLs must be verified before drafting against installed portal boards or known ATS apexes.
- The 6 standard ATS apex domains must be checked: greenhouse.io, lever.co,
myworkdayjobs.com (or workday.com), ashbyhq.com, smartrecruiters.com, workable.com.
- Look-alike attacks (prefixes, suffixes, userinfo tricks) must fail closed.
- Any other host must be named plainly in the output as unverified.
"""
import re
import unittest
from pathlib import Path
from urllib.parse import urlparse
REPO = Path(__file__).resolve().parent.parent
APPLY_COMMAND_FILE = REPO / ".claude" / "commands" / "apply.md"
KNOWN_ATS_APEXES = {
"greenhouse.io",
"lever.co",
"myworkdayjobs.com",
"workday.com",
"ashbyhq.com",
"smartrecruiters.com",
"workable.com",
}
SHIPPED_PORTAL_HOSTS = {
"jobindex.dk",
"linkedin.com",
"jobnet.dk",
"jobbank.dk",
"jobdanmark.dk",
"freehire.me",
}
def classify_posting_host(url_str: str, installed_portals: set[str] = SHIPPED_PORTAL_HOSTS) -> tuple[str, str]:
"""Reference implementation of the host provenance rule in /apply Step 1.
Returns (tier, host), where tier is one of:
- 'installed_portal'
- 'official_ats'
- 'unverified'
"""
try:
parsed = urlparse(url_str)
host = (parsed.hostname or "").lower().strip()
except Exception:
return "unverified", ""
if not host:
return "unverified", ""
# Check installed portal boards (exact match or subdomain match)
for portal in installed_portals:
if host == portal or host.endswith(f".{portal}"):
return "installed_portal", host
# Check known official ATS apexes (exact match or subdomain match)
for apex in KNOWN_ATS_APEXES:
if host == apex or host.endswith(f".{apex}"):
return "official_ats", host
return "unverified", host
class ApplyHostVerificationSpecTests(unittest.TestCase):
def setUp(self):
self.text = APPLY_COMMAND_FILE.read_text(encoding="utf-8")
step1_match = re.search(r"## Step 1: DRAFTER - Evaluate Fit(.*?)(?=## Step 2:)", self.text, re.DOTALL)
self.assertTrue(step1_match, "Step 1 must exist in apply.md")
self.step1_text = step1_match.group(1)
def test_step1_contains_source_host_verification_heading(self):
self.assertIn("Source Host Verification", self.step1_text)
def test_step1_documents_all_six_ats_apexes(self):
for apex in ["greenhouse.io", "lever.co", "myworkdayjobs.com", "ashbyhq.com", "smartrecruiters.com", "workable.com"]:
self.assertIn(apex, self.step1_text, f"Step 1 must specify ATS apex: {apex}")
def test_step1_documents_look_alike_fail_closed_rules(self):
self.assertIn("evil-greenhouse.io", self.step1_text)
self.assertIn("fail closed", self.step1_text)
def test_step1_requires_unverified_hosts_to_be_named_plainly(self):
self.assertIn("Unverified source host", self.step1_text)
def test_classifier_identifies_official_ats_subdomains(self):
urls = [
"https://boards.greenhouse.io/acme/jobs/12345",
"https://job-boards.greenhouse.io/acme/jobs/12345",
"https://jobs.lever.co/corp/67890",
"https://acme.myworkdayjobs.com/en-US/Careers/job/1",
"https://jobs.ashbyhq.com/startup/abc-123",
"https://jobs.smartrecruiters.com/Enterprise/456",
"https://apply.workable.com/tech-corp/j/789/",
]
for url in urls:
tier, host = classify_posting_host(url)
self.assertEqual(tier, "official_ats", f"{url} should classify as official_ats, got {tier}")
def test_classifier_identifies_installed_portal_hosts(self):
urls = [
"https://www.jobindex.dk/jobannonce/12345",
"https://www.linkedin.com/jobs/view/999999",
"https://jobnet.dk/find-job/8888",
"https://jobbank.dk/job/7777",
"https://freehire.me/job/6666",
]
for url in urls:
tier, host = classify_posting_host(url)
self.assertEqual(tier, "installed_portal", f"{url} should classify as installed_portal, got {tier}")
def test_classifier_fails_closed_on_look_alikes_and_unverified_hosts(self):
suspicious = [
"https://evil-greenhouse.io/job/1",
"https://boards.greenhouse.io.evil.com/job/1",
"https://boards.greenhouse.io@evil-domain.com/job/1",
"https://myworkdayjobs.com.phishing.net/login",
"https://lever.co.attacker.org/apply",
"https://unknown-board.example.com/posting/123",
]
for url in suspicious:
tier, host = classify_posting_host(url)
self.assertEqual(tier, "unverified", f"{url} must fail closed as unverified, got {tier}")
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
"""Guard for /apply Step 5b's page-count check.
The 2-page CV and 1-page cover letter limits are the hard rules of
05-cv-templates.md and 06-cover-letter-templates.md, and two places defer
their enforcement to `tools/verify_pdf.py --pages`: `verify_layout.py`'s
docstring ("page count is verify_pdf.py's job, and CI runs it") and Step 5b's
own prose, which used to say "Step 5d already runs it". Step 5d's only
invocation is `--dump-text`, and no other step passed `--pages` at all, so
the one rule with a mechanical check had zero runnable implementations in
the workflow. These tests pin that the invocations exist where the prose says
they do, with the counts the guides require, and that no step defers the
check to another step that does not run it.
"""
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
APPLY = REPO / ".claude" / "commands" / "apply.md"
VERIFY_LAYOUT = REPO / "tools" / "verify_layout.py"
def section(path, heading):
"""The body of one markdown section, up to the next heading of any depth."""
text = path.read_text(encoding="utf-8")
start = text.index(heading) + len(heading)
rest = text[start:]
end = re.search(r"^#{1,4} ", rest, re.MULTILINE)
return rest[: end.start()] if end else rest
def page_count_invocations(text):
"""(document path, page count) for every runnable verify_pdf --pages line."""
return re.findall(
r"^python tools/verify_pdf\.py (\S+) --pages (\d+)\s*$", text, re.MULTILINE
)
class ApplyRunsThePageCountCheck(unittest.TestCase):
def setUp(self):
self.step_5b = section(APPLY, "### 5b. Inspect layout")
def test_step_5b_checks_both_documents_with_the_guides_page_limits(self):
invocations = dict(page_count_invocations(self.step_5b))
self.assertEqual(
invocations.get("cv/main_<company>_<role>.pdf"),
"2",
"Step 5b must run verify_pdf.py --pages 2 on the CV - the hard "
"2-page limit has no other mechanical check",
)
self.assertEqual(
invocations.get("cover_letters/cover_<company>_<role>.pdf"),
"1",
"Step 5b must run verify_pdf.py --pages 1 on the cover letter",
)
def test_page_count_runs_before_the_layout_measurement(self):
# verify_layout.py's own docstring declines to check page count because
# verify_pdf.py --pages does; the deferral only holds if that runs first.
first_pages = self.step_5b.index("--pages")
first_layout = self.step_5b.index("verify_layout.py")
self.assertLess(first_pages, first_layout)
def test_no_step_defers_the_check_to_a_step_that_does_not_run_it(self):
text = APPLY.read_text(encoding="utf-8")
self.assertNotIn(
"Step 5d already runs it",
text,
"Step 5d's only verify_pdf call is --dump-text; the page-count "
"invocation lives in 5b and the prose must point there",
)
def test_layout_tools_deferral_is_backed_by_a_runnable_invocation(self):
docstring = VERIFY_LAYOUT.read_text(encoding="utf-8")
self.assertIn("verify_pdf.py --pages", docstring)
self.assertGreaterEqual(
len(page_count_invocations(APPLY.read_text(encoding="utf-8"))),
2,
"verify_layout.py defers page count to verify_pdf.py --pages, so "
"/apply must actually invoke it",
)
if __name__ == "__main__":
unittest.main()
+93
View File
@@ -11,6 +11,7 @@ byte-identical to /outcome's, which is the entire reason for reusing it.
How each reader treats `drafted` is pinned per reader below, because the How each reader treats `drafted` is pinned per reader below, because the
right answer differs between them. right answer differs between them.
""" """
import fnmatch
import re import re
import subprocess import subprocess
import sys import sys
@@ -385,6 +386,98 @@ class DeadlineSurvivesEveryWrite(unittest.TestCase):
self.assertIn(needle, haystack, why) self.assertIn(needle, haystack, why)
class FallbackGlobFindsOneRolesDocuments(unittest.TestCase):
"""The `cv_file` fallback must select one role's documents, not one company's.
`/apply` names drafts `cv/main_<company>_<role><CV_EXT>`, so two roles
at one company differ only in the role half. When the tracker row's
`cv_file`/`cover_letter_file` columns are empty - a row written before
#291, added by hand, or by /outcome's own outside-the-workflow path -
both readers fall back to a glob. A company-prefix glob matches both
roles and the first hit wins silently: /outcome copies it to
`cv_draft.tex`, and its own "leave an existing archived file" rule then
makes the wrong answer permanent (#443).
The globs are extracted from the specs rather than restated here, so
these tests pin what the specs actually say.
"""
COMPANY = "Acme"
ROLES = ("Data Scientist", "ML Engineer", "ML Engineer II")
CASES = [
(OUTCOME, "## Step 3: Archive the Application Materials",
"by the **Subfolder naming** rule in `documents/README.md`",
"the archive locator must derive the stem by the one documented rule, "
"not invent a second derivation that drifts from it"),
(OUTCOME, "## Step 3: Archive the Application Materials",
"Never widen those globs to the company alone",
"without the prohibition the next edit relaxes the glob when it finds "
"no match, which is exactly the wrong-file-recorded-as-submitted case"),
(INTERVIEW, "## Step 1: Load the Application Context",
"by the **Subfolder naming** rule in `documents/README.md`",
"interview's fallback must resolve the same stem /apply wrote"),
(INTERVIEW, "## Step 1: Load the Application Context",
"Never widen those globs to the company alone",
"prep built from the sibling role's CV is a live-conversation failure"),
]
def test_both_readers_glob_the_full_stem(self):
for path, heading, needle, why in self.CASES:
with self.subTest(file=path.name, rule=needle):
self.assertIn(needle, section(path, heading), why)
@staticmethod
def globs(path, heading):
"""The two fallback globs exactly as the spec writes them."""
body = section(path, heading)
found = re.findall(r"`(cv/main_[^`]+|cover_letters/cover_[^`]+)`", body)
return [g for g in found if "*" in g]
def resolve(self, glob, role):
"""Substitute the spec's placeholders the way the reader would."""
stem = ArchiveNameIsOnePathComponent.derive(self.COMPANY, role)
company = ArchiveNameIsOnePathComponent.derive(self.COMPANY, "").rstrip("_")
return glob.replace("<company>_<role>", stem).replace("<company>", company)
def drafted_files(self, ext=".tex"):
"""Exactly what /apply Step 5 leaves in cv/ for two roles at one company."""
return [
"cv/main_%s%s" % (ArchiveNameIsOnePathComponent.derive(self.COMPANY, r), ext)
for r in self.ROLES
]
def test_the_cv_glob_selects_the_row_s_own_role(self):
on_disk = self.drafted_files()
for path, heading in ((OUTCOME, "## Step 3: Archive the Application Materials"),
(INTERVIEW, "## Step 1: Load the Application Context")):
cv_glob = next(g for g in self.globs(path, heading) if g.startswith("cv/"))
for role, expected in zip(self.ROLES, on_disk):
with self.subTest(file=path.name, role=role):
hits = fnmatch.filter(on_disk, self.resolve(cv_glob, role))
self.assertEqual(
hits, [expected],
"%s's fallback glob %r matched %r for role %r. A glob that "
"matches both roles hands /outcome whichever the filesystem "
"returns first, and it archives that as what was submitted."
% (path.name, cv_glob, hits, role),
)
def test_the_glob_finds_a_non_tex_template(self):
"""`/add-template` makes `.typ` a real output; a hardcoded `.tex` misses it."""
on_disk = self.drafted_files(ext=".typ")
cv_glob = next(
g for g in self.globs(OUTCOME, "## Step 3: Archive the Application Materials")
if g.startswith("cv/")
)
hits = fnmatch.filter(on_disk, self.resolve(cv_glob, self.ROLES[0]))
self.assertEqual(
hits, [on_disk[0]],
"the fallback hardcodes an extension, so a template registered by "
"/add-template is invisible to it and /outcome archives nothing",
)
class ArchiveNameIsOnePathComponent(unittest.TestCase): class ArchiveNameIsOnePathComponent(unittest.TestCase):
"""`<company>_<role>` must derive a single path component. """`<company>_<role>` must derive a single path component.
+79
View File
@@ -3,6 +3,7 @@ import unittest
from contextlib import redirect_stderr from contextlib import redirect_stderr
from types import SimpleNamespace from types import SimpleNamespace
from salary_lookup import format_entry
from tools.convert_salary_excel import ( from tools.convert_salary_excel import (
INDEX_PATTERNS, INDEX_PATTERNS,
detect_column_type, detect_column_type,
@@ -391,6 +392,84 @@ class ParseNumericCellLocaleTests(unittest.TestCase):
self.assertEqual(parse_numeric_cell("1.234.567,89"), 1234567.89) self.assertEqual(parse_numeric_cell("1.234.567,89"), 1234567.89)
class BareCountIndexPairingTests(unittest.TestCase):
"""A count/index pair whose headers carry no category word is still a pair.
"Count" + "Index" (Danish "Antal" + "Lønindeks") both strip to an empty
category name, and the pairing loop used to require a non-empty name on
both sides, so the single-category layout the README describes as
"auto-pairs count/index columns" came out as two unrelated standalone
columns. salary_lookup then rendered the count row with "N/A*" for the
index - "too few employees to publish (privacy)" - about a company whose
headcount was right there in the file. The literal name is asserted (not
the module constant) so the cases run, and fail, against the old converter.
"""
DEFAULT_CATEGORY = "all_employees"
def test_bare_english_pair_is_paired_under_the_default_category(self):
ws = FakeWorksheet([
("Company", "City", "Count", "Index"),
("Acme Corp", "Copenhagen", 500, 108.5),
])
companies = parse_sheet(ws)
self.assertEqual(
companies[0]["categories"],
{self.DEFAULT_CATEGORY: {"count": 500, "index": 108.5}},
)
def test_bare_danish_pair_is_paired_under_the_default_category(self):
ws = FakeWorksheet([
("Firma", "By", "Antal", "Lønindeks"),
("Acme Corp", "Aarhus", 500, 108.5),
])
companies = parse_sheet(ws)
self.assertEqual(
companies[0]["categories"],
{self.DEFAULT_CATEGORY: {"count": 500, "index": 108.5}},
)
def test_bare_pair_does_not_cross_pair_with_a_named_category(self):
# The bare pair and the named pair coexist; neither steals the other's
# column, and a lone "Antal" with no bare index column stays standalone
# (pinned separately by test_standalone_count_column_is_stored_as_count_not_index).
ws = FakeWorksheet([
("Company", "Antal", "IT Count", "IT Index", "Lønindeks"),
("Acme Corp", 500, 30, 112.0, 108.5),
])
companies = parse_sheet(ws)
self.assertEqual(
companies[0]["categories"],
{
self.DEFAULT_CATEGORY: {"count": 500, "index": 108.5},
"it": {"count": 30, "index": 112.0},
},
)
def test_lookup_renders_the_bare_pair_as_one_row_without_the_privacy_footnote_firing(self):
# End to end through the documented path: converter output is what
# salary_lookup.format_entry displays during /apply. Before the fix the
# same sheet produced a "Count 500 N/A*" row plus an "Index - 108.5"
# row - the N/A* asserting a privacy suppression that never happened.
ws = FakeWorksheet([
("Company", "City", "Count", "Index"),
("Acme Corp", "Copenhagen", 500, 108.5),
])
entry = parse_sheet(ws)[0]
rendered = format_entry(entry, {"index_baseline": 100, "index_label": "Index"})
self.assertNotIn("N/A*", rendered.split("* N/A =")[0])
self.assertRegex(rendered, r"All Employees\s+500\s+108\.5\s+\+8\.5%")
self.assertNotRegex(rendered, r"^\s*Count\s+500", )
class CompoundCategoryPairingTests(unittest.TestCase): class CompoundCategoryPairingTests(unittest.TestCase):
def test_parse_sheet_pairs_danish_compound_index_with_count(self): def test_parse_sheet_pairs_danish_compound_index_with_count(self):
# "Lønindeks alle" is *detected* as an index column via # "Lønindeks alle" is *detected* as an index column via
+53
View File
@@ -0,0 +1,53 @@
"""Tests for the /expand command specification."""
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
EXPAND_COMMAND_FILE = REPO_ROOT / ".claude" / "commands" / "expand.md"
class ExpandCommandTests(unittest.TestCase):
def test_expand_command_file_exists(self):
self.assertTrue(EXPAND_COMMAND_FILE.exists(), "expand.md must exist under .claude/commands/")
def test_expand_command_file_starts_with_correct_header(self):
text = EXPAND_COMMAND_FILE.read_text(encoding="utf-8")
first_line = text.lstrip().splitlines()[0]
self.assertTrue(
first_line.startswith("# /expand"),
f"Command file must start with '# /expand', got: {first_line!r}",
)
def test_expand_covers_all_discovery_sources(self):
text = EXPAND_COMMAND_FILE.read_text(encoding="utf-8")
sources = [
"documents/cv/",
"documents/linkedin/",
"documents/diplomas/",
"documents/references/",
"GitHub Profile",
]
for src in sources:
self.assertIn(src, text, f"expand.md must include discovery source: {src}")
def test_expand_maps_github_projects_to_independent_projects_section(self):
text = EXPAND_COMMAND_FILE.read_text(encoding="utf-8")
self.assertIn("## Independent Projects", text)
self.assertIn("Independent Projects & Portfolio", text)
self.assertIn("GitHub — repo-name", text)
self.assertIn("Portfolio & projects grounded in code", text)
self.assertNotIn("documents/projects/", text)
def test_expand_enforces_additive_and_confirmation_principles(self):
text = EXPAND_COMMAND_FILE.read_text(encoding="utf-8")
self.assertIn("Additive only", text)
self.assertIn("User confirms before writing", text)
self.assertIn("`all`", text)
self.assertIn("`review`", text)
self.assertIn("`skip`", text)
if __name__ == "__main__":
unittest.main()
+137
View File
@@ -0,0 +1,137 @@
"""Tests for tools/job_key.py - the canonical seen_jobs.json key function.
/scrape's key rule was prose only, so runs slugified inconsistently and the
state file accumulated two failures: keys carrying "/", "," and "&" that break
the archive-folder path `/apply`/`/outcome` derive from company+role, and the
same job stored twice under two different truncations of a long title. These
pin the fix - a pure, deterministic function of company+title(+url) - and the
audit that finds both failure classes in an existing file.
"""
import json
import subprocess
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools"))
from job_key import is_canonical, is_legacy_shape, make_key, slugify # noqa: E402
REPO = Path(__file__).resolve().parent.parent
TOOL = REPO / "tools" / "job_key.py"
class Slugify(unittest.TestCase):
def test_basic(self):
self.assertEqual(slugify("Acme Corp"), "acme-corp")
def test_strips_punctuation_that_breaks_paths(self):
self.assertEqual(slugify("Ops Consulting, LLC"), "ops-consulting-llc")
self.assertEqual(slugify("Penetration Tester / Red Teamer"), "penetration-tester-red-teamer")
self.assertEqual(slugify("Junior Cybersecurity Analyst (OT/IoT)"), "junior-cybersecurity-analyst-ot-iot")
def test_non_latin_script_reduces_to_empty(self):
self.assertEqual(slugify("시큐리온"), "")
self.assertEqual(slugify("Код Безопасности"), "")
class MakeKey(unittest.TestCase):
def test_shape(self):
key = make_key("Acme Corp", "SOC Analyst (L2)")
self.assertEqual(key, "acme-corp_soc-analyst-l2")
self.assertTrue(is_canonical(key))
def test_deterministic_across_calls(self):
title = "Cyber Intelligence Center Security Analyst with an unusually long title"
self.assertEqual(make_key("Deloitte", title), make_key("Deloitte", title))
def test_long_titles_never_collide_after_truncation(self):
"""The bug that produced two Deloitte entries for one posting: two
runs truncated the same long title at different points. A hash of the
full slug makes truncation deterministic instead of lossy."""
a = make_key("Deloitte", "Cyber Intelligence Center Security Analyst with trailing text A")
b = make_key("Deloitte", "Cyber Intelligence Center Security Analyst with trailing text B")
self.assertNotEqual(a, b)
def test_non_latin_title_falls_back_to_the_portal_job_id(self):
key = make_key(
"SecuriON",
"안드로이드 앱(악성코드) 분석가 채용",
url="https://kr.linkedin.com/jobs/view/x-4461771225",
)
self.assertEqual(key, "securion_4461771225")
def test_non_latin_title_with_no_url_id_still_produces_a_canonical_key(self):
key = make_key("SecuriON", "안드로이드 앱 분석가", url="")
self.assertTrue(is_canonical(key))
self.assertNotEqual(key, "securion_")
def test_non_latin_company_falls_back_without_producing_a_bare_prefix(self):
key = make_key("Код Безопасности", "Malware Analytic", url="")
self.assertTrue(is_canonical(key))
self.assertFalse(key.startswith("_"))
class CanonicalAndLegacyShape(unittest.TestCase):
def test_canonical_accepts_company_underscore_title(self):
self.assertTrue(is_canonical("acme-corp_soc-analyst"))
def test_canonical_rejects_path_breaking_characters(self):
for bad in ("deloitte_junior-cybersecurity-analyst-(ot/iot)",
"neverhack-estonia_penetration-tester-/-red-teamer",
"ops-consulting,-llc_malware-analyst",
"",
"securion_"):
self.assertFalse(is_canonical(bad), f"{bad!r} should not be canonical")
def test_legacy_three_part_shape_is_flagged_separately_from_malformed(self):
self.assertTrue(is_legacy_shape("nviso-security_soc-analyst_athens"))
self.assertFalse(is_canonical("nviso-security_soc-analyst_athens"))
# A malformed key (bad characters) is never also reported as legacy shape.
self.assertFalse(is_legacy_shape("deloitte_junior-cybersecurity-analyst-(ot/iot)"))
class AuditCLI(unittest.TestCase):
def run_audit(self, seen: dict) -> tuple[dict, int]:
import tempfile
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as fh:
json.dump({"seen": seen}, fh)
path = fh.name
proc = subprocess.run(
[sys.executable, str(TOOL), "--audit", path], capture_output=True, text=True
)
return json.loads(proc.stdout), proc.returncode
def test_clean_state_exits_zero(self):
report, code = self.run_audit({"acme_soc-analyst": {"company": "Acme", "title": "SOC Analyst"}})
self.assertEqual(code, 0)
self.assertEqual(report["malformed_keys"], [])
self.assertEqual(report["duplicate_urls"], {})
def test_malformed_key_exits_nonzero(self):
report, code = self.run_audit(
{"deloitte_junior-cybersecurity-analyst-(ot/iot)": {"company": "Deloitte", "title": "x"}}
)
self.assertEqual(code, 1)
self.assertIn("deloitte_junior-cybersecurity-analyst-(ot/iot)", report["malformed_keys"])
def test_duplicate_url_exits_nonzero(self):
report, code = self.run_audit(
{
"a": {"company": "Acme", "title": "x", "url": "https://x/1"},
"b": {"company": "Acme", "title": "y", "url": "https://x/1"},
}
)
self.assertEqual(code, 1)
self.assertIn("https://x/1", report["duplicate_urls"])
def test_legacy_shape_alone_does_not_fail_the_audit(self):
"""Harmless drift, not damage - the sweep-worthy rewrite is a decision
the maintainer makes, not something the audit enforces."""
report, code = self.run_audit({"acme_soc-analyst_athens": {"company": "Acme", "title": "x"}})
self.assertEqual(code, 0)
self.assertIn("acme_soc-analyst_athens", report["legacy_three_part_keys"])
if __name__ == "__main__":
unittest.main()
+40
View File
@@ -136,5 +136,45 @@ class TestAtsExtractionEncoding(unittest.TestCase):
self.assert_pdftotext_commands_pin_utf8(CV_TEMPLATES) self.assert_pdftotext_commands_pin_utf8(CV_TEMPLATES)
class TestPdflatexFontEncodingGuard(unittest.TestCase):
"""#384: the pdflatex fallback must load T1 fontenc, and only under pdflatex.
Without T1, pdflatex stores accented letters decomposed in the text layer
(`e` + U+0300), so an ATS keyword match on `Genève` fails while the PDF
looks right. moderncv 2.5 loads T1 itself; the apt-packaged 2.3.1 does not.
The line must be guarded so the documented lualatex path is untouched.
"""
GUARDED_FONTENC = re.compile(r"\\ifpdftex\s*\\usepackage\[T1\]\{fontenc\}\s*\\fi")
def assert_has_guarded_fontenc(self, path):
text = path.read_text(encoding="utf-8")
self.assertRegex(
text,
self.GUARDED_FONTENC,
f"{path.name} must carry `\\ifpdftex\\usepackage[T1]{{fontenc}}\\fi` so a "
"pdflatex fallback keeps accents precomposed in the text layer",
)
unguarded = [
f"{path.name}:{lineno}: {line.strip()}"
for lineno, line in enumerate(text.splitlines(), 1)
if "fontenc" in line
and not line.lstrip().startswith("%")
and not self.GUARDED_FONTENC.search(line)
]
self.assertEqual(
unguarded,
[],
"fontenc must stay inside the \\ifpdftex guard - lualatex output "
"must not change:\n" + "\n".join(unguarded),
)
def test_example_cv_guards_fontenc_for_pdflatex(self):
self.assert_has_guarded_fontenc(EXAMPLE_CV)
def test_cv_guide_preamble_guards_fontenc_for_pdflatex(self):
self.assert_has_guarded_fontenc(CV_TEMPLATES)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+65
View File
@@ -0,0 +1,65 @@
"""Guards for /outcome's stale sweep branch (Step 2c).
Pins the invariants for batch-resolving quiet applications:
- Step 0 documents `stale` / `sweep` and `stale <N>` / `sweep <N>`.
- Step 1.3 offers stale sweep when open rows exceed 60 days quiet.
- Step 2c defines the Stale Sweep Branch.
- Drafted applications are strictly excluded (never submitted).
- The default threshold is 60 days quiet.
- User confirmation (all, select, skip) is strictly required before writing.
- Status is resolved to canonical 'no_response' spelling.
"""
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
COMMAND = REPO / ".claude" / "commands" / "outcome.md"
class OutcomeStaleBranchSpecTests(unittest.TestCase):
def setUp(self):
self.text = COMMAND.read_text(encoding="utf-8")
def test_stale_argument_documented_in_step0(self):
self.assertIn("`stale` or `sweep`", self.text)
self.assertIn("`stale <N>` or `sweep <N>`", self.text)
def test_step1_suggests_stale_sweep(self):
self.assertIn("/outcome stale", self.text)
self.assertIn("60+ days", self.text)
def test_step2c_section_exists(self):
self.assertIn("## Step 2c: Stale Sweep Branch", self.text)
def test_drafted_rows_excluded_from_stale_candidates(self):
match = re.search(r"## Step 2c: Stale Sweep Branch(.*?)(?=## Step 3:)", self.text, re.DOTALL)
self.assertTrue(match, "Step 2c must exist")
step2c = match.group(1)
self.assertIn("neither final nor `drafted`", step2c)
self.assertIn("never submitted and cannot receive a response", step2c)
def test_default_60_day_threshold(self):
match = re.search(r"## Step 2c: Stale Sweep Branch(.*?)(?=## Step 3:)", self.text, re.DOTALL)
self.assertTrue(match)
step2c = match.group(1)
self.assertIn("60 days", step2c)
def test_user_confirmation_options_required(self):
match = re.search(r"## Step 2c: Stale Sweep Branch(.*?)(?=## Step 3:)", self.text, re.DOTALL)
self.assertTrue(match)
step2c = match.group(1)
self.assertIn("`all`", step2c)
self.assertIn("`select`", step2c)
self.assertIn("`skip`", step2c)
def test_resolves_to_canonical_no_response(self):
match = re.search(r"## Step 2c: Stale Sweep Branch(.*?)(?=## Step 3:)", self.text, re.DOTALL)
self.assertTrue(match)
step2c = match.group(1)
self.assertIn("no_response", step2c)
if __name__ == "__main__":
unittest.main()
+33
View File
@@ -25,6 +25,39 @@ from salary_lookup import (
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
class FormatEntryTests(unittest.TestCase): class FormatEntryTests(unittest.TestCase):
PRIVACY_FOOTNOTE = "* N/A = Too few employees to publish (privacy)"
def test_privacy_footnote_is_omitted_when_no_row_is_suppressed(self):
# The footnote explains the N/A* marker. Printed under a table where
# every row has an index, it asserts a privacy suppression that never
# happened (residual noted on #470).
entry = {
"company": "Example Corp",
"city": "",
"categories": {"all_employees": {"count": 500, "index": 108.5}},
}
rendered = format_entry(entry, {"index_baseline": 100, "index_label": "Index"})
self.assertNotIn("N/A", rendered)
self.assertNotIn(self.PRIVACY_FOOTNOTE, rendered)
self.assertRegex(rendered, r"All Employees\s+500\s+108\.5\s+\+8\.5%")
def test_privacy_footnote_is_printed_when_a_row_is_suppressed(self):
entry = {
"company": "Example Corp",
"city": "",
"categories": {
"all_employees": {"count": 500, "index": 108.5},
"small_team": {"count": 3, "index": None},
},
}
rendered = format_entry(entry, {"index_baseline": 100, "index_label": "Index"})
self.assertRegex(rendered, r"Small Team\s+3\s+N/A\*")
self.assertIn(self.PRIVACY_FOOTNOTE, rendered)
def test_zero_count_is_displayed_as_zero(self): def test_zero_count_is_displayed_as_zero(self):
entry = { entry = {
"company": "Example Corp", "company": "Example Corp",
+16
View File
@@ -136,5 +136,21 @@ class SeenJobsPostingDateTests(unittest.TestCase):
) )
class SeenJobsDedupContinuityTests(unittest.TestCase):
"""The new key rule must not replay jobs stored under legacy keys."""
def test_existing_urls_are_seen_regardless_of_key(self):
text = SCRAPER_SKILL.read_text(encoding="utf-8")
self.assertRegex(
text,
r"URL matches any existing `seen_jobs\.json` entry, regardless of\s+that entry's key",
"legacy seen_jobs entries must be matched by URL during the key-rule transition",
)
def test_step4_presentation_mentions_url_deduplication(self):
text = SCRAPER_SKILL.read_text(encoding="utf-8")
self.assertRegex(text, r"matched by URL or\s+company\+title")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+30
View File
@@ -9,9 +9,12 @@ were not, so a full Path B/C run left `[YOUR_NAME]`, `[YOUR_EMAIL]` and
on the drafter noticing. A real user (#420) ran `/setup` and then hand-edited both on the drafter noticing. A real user (#420) ran `/setup` and then hand-edited both
files to close the gap. files to close the gap.
""" """
import os
import unittest import unittest
from pathlib import Path from pathlib import Path
UPSTREAM = "MadsLorentzen/ai-job-search"
REPO = Path(__file__).resolve().parent.parent REPO = Path(__file__).resolve().parent.parent
COMMAND = REPO / ".claude" / "commands" / "setup.md" COMMAND = REPO / ".claude" / "commands" / "setup.md"
SKILL_DIR = REPO / ".claude" / "skills" / "job-application-assistant" SKILL_DIR = REPO / ".claude" / "skills" / "job-application-assistant"
@@ -67,6 +70,10 @@ class SetupStep3ContactBlocks(unittest.TestCase):
self.assertIn("06-cover-letter-templates.md", summary) self.assertIn("06-cover-letter-templates.md", summary)
@unittest.skipIf(
os.environ.get("GITHUB_REPOSITORY", UPSTREAM) != UPSTREAM,
"template-placeholder guard targets the pristine upstream template; forks personalize 05-cv-templates.md and 06-cover-letter-templates.md via /setup",
)
class TemplatesStillCarryThePlaceholders(unittest.TestCase): class TemplatesStillCarryThePlaceholders(unittest.TestCase):
"""The instructions above target real tokens; if a template renames them, """The instructions above target real tokens; if a template renames them,
the instruction and this test must move together.""" the instruction and this test must move together."""
@@ -83,5 +90,28 @@ class TemplatesStillCarryThePlaceholders(unittest.TestCase):
self.assertIn("\\signature{[YOUR_NAME]}", text) self.assertIn("\\signature{[YOUR_NAME]}", text)
class SetupPathAProjectsIngestion(unittest.TestCase):
"""Guards for /setup Path A document ingestion of documents/projects/."""
def setUp(self):
self.text = COMMAND.read_text(encoding="utf-8")
self.sections = _sections(self.text)
def test_step0_scan_includes_projects(self):
step0 = self.sections["Step 0: Welcome & Choose Path"]
self.assertIn("projects/", step0)
def test_step_a1_inventory_includes_projects(self):
self.assertIn("**projects/**:", self.text)
def test_step_a3_parsing_includes_projects_spec(self):
self.assertIn("`projects/` documents:", self.text)
self.assertIn("measurable outcomes", self.text)
def test_step_a5_and_a6_map_to_independent_projects(self):
self.assertIn("## Independent Projects", self.text)
self.assertIn("New independent project:", self.text)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+135
View File
@@ -0,0 +1,135 @@
"""Guards for the rule that keeps free-form `notes` from breaking a tracker row.
No writer in this framework emits a quoted tracker field, so a comma inside
`notes` splits the row - for the `csv.DictReader` in `tools/rank_state.py` as
much as for a naive split - and shifts `cv_file`, `cover_letter_file` and
`source` a column left. A line break is worse: it ends the row. Two writers put
free-form text into `notes`: `/gmail-sync` Step 7a copies an email subject, and
`/outcome` Step 4 writes a short note of its own. The fixed-format writers
(`followed up YYYY-MM-DD`, `stale resolved no_response (YYYY-MM-DD)`,
`redrafted`) cannot contain the characters and are not listed.
The spec IS the implementation, so the guard is `CASES`: each rule must sit on
the line that instructs the append, not merely somewhere in the section. The
shape tests below it parse with `csv.DictReader` and document why the rule
exists; they pass on master too.
"""
import csv
import io
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
COMMANDS = REPO / ".claude" / "commands"
GMAIL_SYNC = COMMANDS / "gmail-sync.md"
OUTCOME = COMMANDS / "outcome.md"
TRACKER_HEADER = (
"date,company,sector,role,role_type,channel,status,contact_person,"
"fit_rating,notes,cv_file,cover_letter_file,source,deadline"
)
def section(path, heading):
"""The body of one markdown section, up to the next heading of any depth."""
text = path.read_text(encoding="utf-8")
start = text.index(heading) + len(heading)
rest = text[start:]
end = re.search(r"^#{1,4} ", rest, re.MULTILINE)
return rest[: end.start()] if end else rest
class FreeFormNotesWritersStateTheRule(unittest.TestCase):
"""Format: (path, heading, line_anchor, rule, why)"""
CASES = [
(
GMAIL_SYNC,
"### Step 7a: Write Approved Updates",
"append to `notes`",
"with every comma, double quote and line break deleted from the subject first",
"Step 7a item 2 deliberately keeps the subject verbatim in `outcome.md`, "
"so the rule must sit on the tracker append, not anywhere in the step",
),
(
OUTCOME,
"## Step 4: Update the Tracker",
"append a short dated note",
"containing no commas, double quotes or line breaks",
"Step 4 is the primary status-update path and its note is written "
"free-form - `rejected, no feedback given` is the natural sentence",
),
]
def test_rule_is_stated_where_the_append_happens(self):
for path, heading, anchor, rule, why in self.CASES:
with self.subTest(path=path.name, heading=heading):
lines = [l for l in section(path, heading).splitlines() if anchor in l]
self.assertEqual(len(lines), 1, f"expected one append instruction: {why}")
self.assertIn(rule, lines[0], why)
class NotesShapeUnderTheShippedReader(unittest.TestCase):
"""Why the rule exists, demonstrated with the reader the repo ships."""
SUBJECT = 'Re: Your application, Data Scientist - "next steps"'
def test_sanitised_note_keeps_the_row_parseable(self):
safe = self.SUBJECT.replace(",", "").replace('"', "")
rows = self._parse(f'2026-09-12 gmail-sync: acknowledged ("{safe}")')
self.assertEqual(len(rows), 1, "the note must not end the row early")
row = rows[0]
self.assertIsNone(row.get(None), "the row must be no wider than the header")
self.assertEqual(row["cv_file"], "cv/main_acme_data_scientist.tex")
self.assertEqual(
row["cover_letter_file"], "cover_letters/cover_acme_data_scientist.tex"
)
self.assertEqual(row["source"], "linkedin")
def test_a_comma_in_the_note_shifts_the_columns(self):
for note in (
f'2026-09-12 gmail-sync: acknowledged ("{self.SUBJECT}")',
"2026-09-12 rejected, no feedback given",
):
with self.subTest(note=note):
row = self._parse(note)[0]
self.assertIsNotNone(row.get(None), "the comma must widen the row")
self.assertNotEqual(row["cv_file"], "cv/main_acme_data_scientist.tex")
self.assertNotEqual(row["source"], "linkedin")
def test_a_line_break_in_the_note_splits_the_row_in_two(self):
rows = self._parse('2026-09-12 gmail-sync: acknowledged ("Re: update\nlater")')
self.assertEqual(len(rows), 2)
self.assertIsNone(rows[0]["cv_file"], "the first row ends mid-note")
@classmethod
def _parse(cls, notes):
stream = io.StringIO(TRACKER_HEADER + "\n" + cls._row(notes) + "\n")
return list(csv.DictReader(stream))
@staticmethod
def _row(notes):
return ",".join(
[
"2026-09-01",
"Acme",
"tech",
"Data Scientist",
"full_time",
"portal",
"applied",
"",
"8",
notes,
"cv/main_acme_data_scientist.tex",
"cover_letters/cover_acme_data_scientist.tex",
"linkedin",
"2026-09-30",
]
)
if __name__ == "__main__":
unittest.main()
+168
View File
@@ -0,0 +1,168 @@
"""Offline tests for tools/verify_layout.py.
Every case is built from synthetic Page/Line geometry rather than a compiled
PDF, so the suite needs neither Poppler nor a LaTeX toolchain - matching the
repo's CI policy of keeping the Python tool tests self-contained.
The cases marked SILENT FAILURE are the ones that motivated the tool: each
describes a document that compiles cleanly, reports the expected page count,
and passes tools/verify_pdf.py, while the rendered page is visibly broken.
"""
import io
import subprocess
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
from tools.verify_layout import Line, Page, find_orphans, main, parse_pdf, report
A4_HEIGHT = 842.0
def line(top: float, left: float = 50.0, height: float = 10.0, text: str = "x") -> Line:
return Line(top=top, bottom=top + height, left=left, height=height, text=text)
class TestGapAndBottomSpace(unittest.TestCase):
def setUp(self):
# Three body lines, then a 322pt jump, then the page-number footer.
self.holed = Page(
A4_HEIGHT,
[line(50), line(64), line(78), line(400), line(770, text="1/2")],
)
def test_largest_gap_reports_size_and_position(self):
"""SILENT FAILURE: the hole an ejected \\cventry leaves behind."""
gap, y = self.holed.largest_gap()
self.assertEqual((round(gap), round(y)), (322, 78))
def test_bottom_space_ignores_the_footer_band(self):
"""Measured to the last body line (y410), not to the page number at y770."""
self.assertEqual(round(self.holed.bottom_space), 432)
def test_page_with_no_body_lines_is_empty(self):
self.assertTrue(Page(A4_HEIGHT, []).empty)
def test_report_flags_the_hole(self):
with redirect_stdout(io.StringIO()): # report() prints its per-page measurements
problems = report(Path("synthetic"), [self.holed])
self.assertTrue(any("hole" in m for m in problems), problems)
class TestFooterBand(unittest.TestCase):
def test_single_line_in_band_is_just_the_page_number(self):
self.assertFalse(Page(A4_HEIGHT, [line(50), line(800, text="2/2")]).footer_crowded)
def test_two_lines_in_band_means_body_text_spilled_in(self):
"""SILENT FAILURE: \\enlargethispage pushing body text over the footer."""
self.assertTrue(Page(A4_HEIGHT, [line(50), line(780), line(800)]).footer_crowded)
class TestHeadingAndIndentDetection(unittest.TestCase):
def setUp(self):
self.page = Page(
A4_HEIGHT,
[
line(50, height=16.0, text="Professional Experience"),
line(80, left=50.0),
line(94, left=70.0),
],
)
def test_taller_line_is_a_heading(self):
self.assertTrue(self.page.is_heading(self.page.body[0]))
self.assertFalse(self.page.is_heading(self.page.body[1]))
def test_left_edge_separates_bullets_from_headers(self):
self.assertTrue(self.page.is_indented(self.page.body[2]))
self.assertFalse(self.page.is_indented(self.page.body[1]))
class TestOrphans(unittest.TestCase):
def test_page_ending_on_a_section_heading(self):
"""SILENT FAILURE: a heading stranded at the bottom, content overleaf."""
p1 = Page(A4_HEIGHT, [line(50), line(64), line(700, height=16.0, text="Education")])
p2 = Page(A4_HEIGHT, [line(60, text="Example University"), line(74, left=70.0)])
self.assertTrue(any("ends on the section heading" in m for m in find_orphans([p1, p2])))
def test_entry_header_orphaned_from_its_bullets(self):
"""SILENT FAILURE: the \\cventry title on one page, its bullets on the next."""
q1 = Page(A4_HEIGHT, [line(50), line(700, left=50.0, text="Software Engineer")])
q2 = Page(A4_HEIGHT, [line(60, left=70.0, text="- built the thing")])
self.assertTrue(any("orphaned from its bullets" in m for m in find_orphans([q1, q2])))
def test_lone_list_marker_is_a_split_bullet_not_an_orphaned_header(self):
"""moderncv gives the itemize marker its own bbox line: different defect, different fix."""
m1 = Page(A4_HEIGHT, [line(50), line(700, left=50.0, text="")])
m2 = Page(A4_HEIGHT, [line(60, left=70.0, text="continued item text here")])
self.assertTrue(any("lone list marker" in m for m in find_orphans([m1, m2])))
def test_clean_break_reports_nothing(self):
r1 = Page(A4_HEIGHT, [line(50), line(700, left=50.0)])
r2 = Page(A4_HEIGHT, [line(60, left=50.0)])
self.assertEqual(find_orphans([r1, r2]), [])
def test_indent_is_judged_against_the_document_margin(self):
"""A page that OPENS with bullets must not mistake their indent for its margin."""
s1 = Page(A4_HEIGHT, [line(50, left=50.0), line(700, left=50.0, text="Data Analyst")])
s2 = Page(A4_HEIGHT, [line(60, left=70.0, text="- first bullet")])
self.assertTrue(any("orphaned from its bullets" in m for m in find_orphans([s1, s2])))
class TestExtractorFailure(unittest.TestCase):
"""A broken extractor must not masquerade as a broken document.
Git for Windows ships an xpdf-based pdftotext with no -bbox flag; it shadows
Poppler in a default PATH and exits 99. Reported as a layout problem it would
send /apply chasing a phantom hole, so it has to land on the skip path.
"""
def test_pdftotext_without_bbox_raises_a_skippable_error(self):
failure = subprocess.CalledProcessError(99, "pdftotext", stderr="Error: unknown flag")
with patch("tools.verify_layout.shutil.which", return_value="/usr/bin/pdftotext"), patch(
"tools.verify_layout.subprocess.run", side_effect=failure
):
with self.assertRaisesRegex(RuntimeError, "bounding boxes"):
parse_pdf(Path("cv/main_example.pdf"))
def test_poppler_abort_on_empty_info_string_names_that_cause_too(self):
"""Poppler 26.0x before 26.05 aborts -bbox on an empty Info-dict string, e.g.
the empty /Title hyperref writes when pdftitle is unset (#451). That crash is
not the xpdf-shadowing case - it has no -bbox flag and exits 99 - so the
message must name both, not just the one the exit code happens to match.
"""
failure = subprocess.CalledProcessError(
1,
"pdftotext",
stderr="libc++abi: terminating due to uncaught exception of type "
"std::out_of_range: basic_string",
)
with patch("tools.verify_layout.shutil.which", return_value="/usr/bin/pdftotext"), patch(
"tools.verify_layout.subprocess.run", side_effect=failure
):
with self.assertRaisesRegex(RuntimeError, "bounding boxes") as ctx:
parse_pdf(Path("cv/main_example.pdf"))
message = str(ctx.exception)
self.assertIn("xpdf", message)
self.assertIn("Poppler aborted", message)
self.assertIn("hyperref", message)
def test_missing_poppler_raises_a_skippable_error(self):
with patch("tools.verify_layout.shutil.which", return_value=None):
with self.assertRaisesRegex(RuntimeError, "not found"):
parse_pdf(Path("cv/main_example.pdf"))
def test_extractor_failure_exits_2_not_1(self):
"""Exit 1 means "your document is broken"; a dead extractor must never claim that."""
with patch("tools.verify_layout.parse_pdf", side_effect=RuntimeError("no -bbox")), patch(
"sys.argv", ["verify_layout.py", __file__]
):
err = io.StringIO()
with redirect_stdout(io.StringIO()), patch("sys.stderr", err):
self.assertEqual(main(), 2)
self.assertIn("skipped:", err.getvalue())
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -7,6 +7,7 @@ from unittest.mock import patch
from tools.verify_pdf import ( from tools.verify_pdf import (
VerificationError, VerificationError,
extract_text_layer, extract_text_layer,
normalize_text,
parse_page_count, parse_page_count,
run_tool, run_tool,
verify_pdf, verify_pdf,
@@ -22,6 +23,44 @@ class ParsePageCountTests(unittest.TestCase):
parse_page_count("Title: Example\n") parse_page_count("Title: Example\n")
class NormalizeTextTests(unittest.TestCase):
"""`--contains` must see through what LaTeX does to plain source text.
Measured on the stock CV compiled with the documented `lualatex` command
(#385): the apostrophe in `Master's` reaches the text layer as U+2019 and
the `--` in `2016--2024` as U+2013, so a whitespace-only fold reports both
keywords missing from a CV that plainly contains them. Under pdflatex
without T1 font encoding, accents arrive decomposed (`e` + U+0300) instead
of precomposed (#384).
"""
def test_folds_curly_apostrophe_to_ascii(self):
self.assertEqual(normalize_text("Master\u2019s degree"), "Master's degree")
self.assertEqual(normalize_text("\u2018quoted\u2019"), "'quoted'")
def test_folds_curly_double_quotes_to_ascii(self):
self.assertEqual(normalize_text("\u201cSix Sigma\u201d"), '"Six Sigma"')
def test_folds_en_and_em_dashes_to_hyphen(self):
self.assertEqual(normalize_text("2016\u20132024"), "2016-2024")
self.assertEqual(normalize_text("role\u2014title"), "role-title")
def test_folds_no_break_space_to_space(self):
self.assertEqual(normalize_text("EUR\u00a0600k"), "EUR 600k")
def test_folds_decomposed_accents_to_nfc(self):
decomposed = "Gene\u0300ve Universite\u0301"
precomposed = "Gen\u00e8ve Universit\u00e9"
self.assertEqual(normalize_text(decomposed), precomposed)
def test_still_collapses_whitespace(self):
self.assertEqual(normalize_text("Professional\n Experience "), "Professional Experience")
def test_fold_is_symmetric(self):
# A user who pastes the curly form from a posting must match an ASCII layer too.
self.assertEqual(normalize_text("Master\u2019s"), normalize_text("Master's"))
class VerifyPdfTests(unittest.TestCase): class VerifyPdfTests(unittest.TestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory() self.temp_dir = tempfile.TemporaryDirectory()
@@ -73,6 +112,41 @@ class VerifyPdfTests(unittest.TestCase):
with self.assertRaisesRegex(VerificationError, "Professional Experience"): with self.assertRaisesRegex(VerificationError, "Professional Experience"):
verify_pdf(self.pdf, required_text=("Professional Experience",)) verify_pdf(self.pdf, required_text=("Professional Experience",))
@patch("tools.verify_pdf._extract_pypdf", return_value=None)
@patch("tools.verify_pdf.run_tool")
def test_required_text_matches_latex_typographic_substitutions(self, mock_run_tool, _pypdf):
# What the stock template's lualatex text layer actually contains for the
# source `Master's degree ... 2016--2024` (code points measured, see class
# docstring of NormalizeTextTests).
mock_run_tool.side_effect = [
"Master\u2019s degree in Statistics. Six Sigma Green Belt, 2016\u20132024.\n",
"Pages: 1\n",
]
verify_pdf(self.pdf, required_text=("Master's degree", "2016-2024"))
@patch("tools.verify_pdf._extract_pypdf", return_value=None)
@patch("tools.verify_pdf.run_tool")
def test_required_text_matches_decomposed_pdflatex_accents(self, mock_run_tool, _pypdf):
mock_run_tool.side_effect = [
"Universite\u0301 de Gene\u0300ve\n", # pdflatex without T1 fontenc
"Pages: 1\n",
]
verify_pdf(self.pdf, required_text=("Universit\u00e9 de Gen\u00e8ve",))
@patch("tools.verify_pdf._extract_pypdf", return_value=None)
@patch("tools.verify_pdf.run_tool")
def test_dump_text_keeps_the_raw_layer_unfolded(self, mock_run_tool, _pypdf):
# The fold is comparison-time only: the ATS parser sees the raw layer, and
# the date-range rule in 05-cv-templates.md needs the en-dash visible here.
mock_run_tool.side_effect = ["2016\u20132024\n", "Pages: 1\n"]
dump = Path(self.temp_dir.name) / "dump.txt"
verify_pdf(self.pdf, required_text=("2016-2024",), dump_text=dump)
self.assertEqual(dump.read_text(encoding="utf-8"), "2016\u20132024\n")
def test_rejects_missing_pdf(self): def test_rejects_missing_pdf(self):
with self.assertRaisesRegex(VerificationError, "PDF does not exist"): with self.assertRaisesRegex(VerificationError, "PDF does not exist"):
verify_pdf(Path(self.temp_dir.name) / "missing.pdf") verify_pdf(Path(self.temp_dir.name) / "missing.pdf")
+13 -3
View File
@@ -52,6 +52,9 @@ COMPOUND_PATTERNS = {"antal", "indeks", "løn", "gennemsnit", "medarbejdere"}
# data. They are dropped at classification so they are not mistaken for a salary # data. They are dropped at classification so they are not mistaken for a salary
# category. Matched as whole tokens only, like other pattern sets. # category. Matched as whole tokens only, like other pattern sets.
ID_PATTERNS = {"id", "personnummer"} ID_PATTERNS = {"id", "personnummer"}
# Category name for a count/index pair whose headers carry no category word at
# all ("Count" + "Index"). Matches the top-level category in README_SALARY_TOOL.md.
DEFAULT_CATEGORY = "all_employees"
def parse_numeric_cell(value): def parse_numeric_cell(value):
@@ -216,7 +219,14 @@ def parse_sheet(ws, sheet_label=None):
else: else:
untyped_cols.append((col_idx, col_header)) untyped_cols.append((col_idx, col_header))
# Pair count/index columns by matching category name # Pair count/index columns by matching category name. A bare "Count" /
# "Index" pair (Danish "Antal" / "Lønindeks") strips to an empty name on
# both sides - the single-category layout the README's "auto-pairs
# count/index columns" line describes. It is still one pair, so it gets
# the README's default category name instead of being emitted as two
# unrelated standalone columns: salary_lookup renders that split as a
# count row whose index reads "N/A*", i.e. "too few employees to publish
# (privacy)", about a company with a published headcount.
categories = [] categories = []
used_counts = set() used_counts = set()
used_indexes = set() used_indexes = set()
@@ -225,8 +235,8 @@ def parse_sheet(ws, sheet_label=None):
for ii, (i_idx, i_header, i_cat) in enumerate(index_cols): for ii, (i_idx, i_header, i_cat) in enumerate(index_cols):
if ii in used_indexes: if ii in used_indexes:
continue continue
if c_cat and i_cat and c_cat == i_cat: if c_cat == i_cat:
cat_name = c_cat.replace(" ", "_").replace("-", "_") cat_name = (c_cat or DEFAULT_CATEGORY).replace(" ", "_").replace("-", "_")
categories.append({ categories.append({
"name": cat_name, "name": cat_name,
"count_col": c_idx, "count_col": c_idx,
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Canonical dedup key for a job posting, and an audit for existing state.
`/scrape` Step 4 keys every seen_jobs.json entry by company+title. The rule was
prose only ("<url_or_company_title_key>"), so each run slugified in its own way
and the state file accumulated two distinct failures:
* Keys carrying characters that break things downstream. `/apply` and
`/outcome` derive an archive folder name from the same company+role pair,
and documents/README.md's subfolder rule exists because a "/" splits that
path across directories. Real examples found in a live workspace:
"deloitte_junior-cybersecurity-analyst-(ot/iot)",
"neverhack-estonia_penetration-tester-/-red-teamer",
"ops-consulting,-llc_malware-analyst".
* The same job stored twice under different keys, because one run truncated
the title at a different point than the next. "deloitte_cyber-intelligence-
center-security-analy" and "deloitte_cyber-intelligence-center-security-
analyst-at" are one posting, one URL, two entries - and dedup is the whole
point of the file.
Both are fixed by making the key a pure, deterministic function of the posting.
Truncation is length-capped *and* disambiguated by a hash of the full slug, so a
long title always produces the same key and two different long titles never
collide.
A title that slugifies to nothing (a posting written in a non-Latin script) has
no usable key half at all - "securion_" was a real entry, and it would have
collided with every future non-Latin posting from that company. Those fall back
to the portal's numeric id from the URL.
Usage:
python3 tools/job_key.py --company "Acme Corp" --title "SOC Analyst (L2)"
python3 tools/job_key.py --audit job_scraper/seen_jobs.json
Exit 0 when a key is produced, or when an audit finds nothing. Exit 1 when an
audit finds violations.
"""
import argparse
import hashlib
import json
import re
import sys
import unicodedata
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
STATE = ROOT / "job_scraper" / "seen_jobs.json"
COMPANY_MAX = 40
TITLE_MAX = 60
HASH_LEN = 6
# Anything outside this set becomes a separator. Deliberately strict: "/" and
# "," are the characters that actually caused damage, and an allowlist cannot
# be surprised by the next punctuation mark a job board invents.
_NON_SLUG = re.compile(r"[^a-z0-9]+")
_JOB_ID = re.compile(r"(\d{6,})")
def slugify(text: str) -> str:
"""Lowercase ASCII slug. Non-Latin scripts legitimately reduce to ''."""
if not text:
return ""
decomposed = unicodedata.normalize("NFKD", str(text))
ascii_only = decomposed.encode("ascii", "ignore").decode("ascii")
return _NON_SLUG.sub("-", ascii_only.lower()).strip("-")
def _cap(slug: str, limit: int) -> str:
"""Cap length without making truncation lossy across runs.
A bare truncation is what produced the duplicate Deloitte entries: two runs
cut the same title at different points and the file gained a second key for
one job. Appending a hash of the *full* slug makes the result deterministic
for a given title and distinct for any other.
"""
if len(slug) <= limit:
return slug
digest = hashlib.sha1(slug.encode("utf-8")).hexdigest()[:HASH_LEN]
return f"{slug[:limit].rstrip('-')}-{digest}"
def make_key(company: str, title: str, url: str = "") -> str:
"""The canonical seen_jobs.json key for one posting."""
company_slug = _cap(slugify(company), COMPANY_MAX) or "unknown-company"
title_slug = _cap(slugify(title), TITLE_MAX)
if not title_slug:
# No Latin characters in the title. The portal's own numeric id is the
# only stable handle left; never emit a bare "company_" prefix.
match = _JOB_ID.search(url or "")
if match:
title_slug = match.group(1)
else:
basis = slugify(unicodedata.normalize("NFKD", str(title or url or "")))
digest = hashlib.sha1((str(title) + str(url)).encode("utf-8")).hexdigest()[:HASH_LEN]
title_slug = basis or f"untitled-{digest}"
return f"{company_slug}_{title_slug}"
# A canonical key is "<company-slug>_<title-slug>": lowercase alphanumerics and
# hyphens on either side of exactly one underscore. The underscore is the
# separator, so it is the one character outside the slug alphabet that belongs.
_CANONICAL = re.compile(r"^[a-z0-9][a-z0-9-]*_[a-z0-9][a-z0-9-]*$")
def is_canonical(key: str) -> bool:
"""Structurally safe as a dedup key and as an archive folder name."""
return bool(key) and bool(_CANONICAL.match(key))
def is_legacy_shape(key: str) -> bool:
"""Old three-part "company_title_location" keys.
Harmless - they carry no path-breaking character - but they are not what
make_key produces, so a later run would store the same job under a new key
and reintroduce a duplicate. Reported apart from real damage so the fix
stays a decision rather than an automatic rename.
"""
return bool(key) and key.count("_") > 1 and all(
re.fullmatch(r"[a-z0-9][a-z0-9-]*", part) for part in key.split("_") if part
)
def audit(path: Path) -> int:
try:
doc = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
print(f"cannot read {path}: {exc}", file=sys.stderr)
return 1
seen = doc.get("seen", doc)
if not isinstance(seen, dict):
print(f"{path}: expected an object of job entries", file=sys.stderr)
return 1
malformed = [k for k in seen if not is_canonical(k) and not is_legacy_shape(k)]
legacy = [k for k in seen if is_legacy_shape(k)]
by_url: dict[str, list[str]] = {}
for key, entry in seen.items():
url = (entry.get("url") or "").rstrip("/")
if url:
by_url.setdefault(url, []).append(key)
duplicates = {u: ks for u, ks in by_url.items() if len(ks) > 1}
# A key that does not match what make_key would produce today is drift, not
# damage: reported separately so a rename is a choice, never automatic.
drift = [
k for k, v in seen.items()
if is_canonical(k) and k != make_key(v.get("company", ""), v.get("title", ""), v.get("url", ""))
]
print(json.dumps({
"entries": len(seen),
"malformed_keys": malformed,
"legacy_three_part_keys": legacy,
"duplicate_urls": duplicates,
"keys_not_matching_current_rule": len(drift),
}, indent=2, ensure_ascii=False))
return 1 if (malformed or duplicates) else 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--company")
ap.add_argument("--title")
ap.add_argument("--url", default="")
ap.add_argument("--audit", nargs="?", const=str(STATE), metavar="STATE_JSON")
args = ap.parse_args()
if args.audit:
return audit(Path(args.audit))
if args.company is None or args.title is None:
ap.error("give --company and --title, or --audit")
print(make_key(args.company, args.title, args.url))
return 0
if __name__ == "__main__":
sys.exit(main())
+5
View File
@@ -53,8 +53,12 @@ ALLOWED_PERMISSIONS = {
"Bash(python3 salary_lookup.py:*)", "Bash(python3 salary_lookup.py:*)",
"Bash(python tools/rank_state.py:*)", "Bash(python tools/rank_state.py:*)",
"Bash(python3 tools/rank_state.py:*)", "Bash(python3 tools/rank_state.py:*)",
"Bash(python tools/job_key.py:*)",
"Bash(python3 tools/job_key.py:*)",
"Bash(python tools/verify_pdf.py:*)", "Bash(python tools/verify_pdf.py:*)",
"Bash(python3 tools/verify_pdf.py:*)", "Bash(python3 tools/verify_pdf.py:*)",
"Bash(python tools/verify_layout.py:*)",
"Bash(python3 tools/verify_layout.py:*)",
"Bash(pdftotext:*)", "Bash(pdftotext:*)",
} }
@@ -80,6 +84,7 @@ REQUIRED_IGNORE_RULES = [
"documents/linkedin/**", "documents/linkedin/**",
"documents/diplomas/**", "documents/diplomas/**",
"documents/references/**", "documents/references/**",
"documents/projects/**",
"documents/applications/**", "documents/applications/**",
"documents/postings/**", "documents/postings/**",
# Belt-and-braces, not the primary guard: nothing writes here. # Belt-and-braces, not the primary guard: nothing writes here.
+335
View File
@@ -0,0 +1,335 @@
#!/usr/bin/env python3
"""Measure a compiled CV or cover letter's page layout, instead of eyeballing it.
The compile-and-inspect loop in `05-cv-templates.md` and the verification checklist in
CLAUDE.md already require the layout properties below. Nothing executes them: they are
checked by looking at the rendered page, which is exactly how they get missed. Each
failure below produces a clean compile, a correct page count, and a PDF that passes
`tools/verify_pdf.py`:
orphaned entry A moderncv \\cventry renders as a tabular, so a job entry is one
unbreakable block. When it does not fit, the whole entry moves to
the next page - or its header lands at the bottom of one page with
the bullets resuming on the next. CLAUDE.md calls this "the most
common failure".
internal hole The space an ejected entry leaves behind. Observed in the wild at
273pt, roughly 19 blank lines, mid-page, on a document whose page
count was correct and whose visual read looked fine.
page ends early A non-final page that stops well short of the bottom.
final page thin A last page mostly empty, which reads as an unfinished document.
footer collision Body text pushed into the page-number band, the usual result of
rescuing a page with \\enlargethispage or a negative \\vspace.
Page count is deliberately NOT checked here: `tools/verify_pdf.py --pages` already does
that, and CI runs it. Two implementations of one rule drift.
Geometry comes from Poppler word bounding boxes (`pdftotext -bbox`). Poppler is optional
repo-wide - since #369 `verify_pdf.py` prefers pypdf and falls back to Poppler - but word
bounding boxes have no pypdf equivalent, so this is the one step that still wants it.
Without it, or with a broken extractor, the check reports `skipped:` and exits 2 rather
than inventing a layout failure. A broken extractor has two distinct causes: an xpdf-based
`pdftotext` (Git for Windows ships one ahead of Poppler in PATH) has no `-bbox` flag at
all, and Poppler 26.0x before 26.05 aborts `-bbox`/`-bbox-layout`/`-htmlmeta` on a PDF
whose Info dictionary carries an empty string in any field - which `hyperref` writes for
every field it does not set, so any `lualatex`/`pdflatex` document built with `hyperref`
and no `\hypersetup{pdftitle=...}` triggers a real Poppler crashing on a legal PDF (#451).
Line height serves
as a font-size proxy to spot section headings; left edge (xMin) separates bullet lines
from entry headers.
The thresholds below are calibrated for the stock moderncv (`cv/`) and cover.cls
(`cover_letters/`) geometry. A template registered via `/add-template` may need them
retuned - an article-class page number sitting outside the 90pt footer band, for
instance, is read as body text and turns the space above it into a phantom hole.
Usage:
python tools/verify_layout.py cv/main_acme_ml_engineer.pdf
python tools/verify_layout.py cover_letters/cover_acme_ml_engineer.pdf
Exit codes: 0 clean, 1 layout problem, 2 bad invocation or no usable extractor.
The shipped `cv/main_example.pdf` exits 1 by design: its placeholder page 2 is mostly
empty, which is the thin-final-page failure the checklist asks you to fix before sending.
Tests live in tests/test_verify_layout.py and run against synthetic pages, so the
suite needs neither Poppler nor a compiled PDF.
"""
from __future__ import annotations
import argparse
import re
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
# A gap larger than this between consecutive lines is a hole, not spacing. Section
# spacing in the stock templates runs to roughly 45pt; 100pt is about seven lines.
GAP_LIMIT_PT = 100.0
# Bottom whitespace on a page that is not the last one. The stock geometry leaves ~85pt.
BOTTOM_LIMIT_FRACTION = 0.25
# A final page emptier than this reads as an unfinished document.
LAST_PAGE_THIN_FRACTION = 0.35
# The page-number footer lives in the bottom margin and is a text line like any other to
# Poppler. Ignore this band when measuring the body, or every page looks like it has a
# hole above its footer.
FOOTER_BAND_PT = 90.0
# A line indented at least this far past the page's left edge is a bullet or a
# continuation, not an entry header or a section heading.
INDENT_PT = 8.0
# A line this much taller than the body median is a section heading.
HEADING_HEIGHT_RATIO = 1.25
PAGE_RE = re.compile(r'<page width="([\d.]+)" height="([\d.]+)">(.*?)</page>', re.S)
WORD_RE = re.compile(
r'<word xMin="([\d.]+)" yMin="([\d.]+)" xMax="[\d.]+" yMax="([\d.]+)">([^<]*)</word>'
)
@dataclass
class Line:
top: float
bottom: float
left: float
height: float
text: str
class Page:
def __init__(self, height: float, lines: list[Line]):
self.height = height
self.lines = sorted(lines, key=lambda l: l.top)
@property
def body(self) -> list[Line]:
cutoff = self.height - FOOTER_BAND_PT
return [l for l in self.lines if l.top < cutoff]
@property
def empty(self) -> bool:
return not self.body
@property
def bottom_space(self) -> float:
return self.height - max(l.bottom for l in self.body) if self.body else self.height
@property
def left_edge(self) -> float:
return min(l.left for l in self.body) if self.body else 0.0
@property
def body_median_height(self) -> float:
heights = sorted(l.height for l in self.body)
return heights[len(heights) // 2] if heights else 0.0
@property
def footer_crowded(self) -> bool:
"""One line in the bottom band is a page number; two means body text spilled in."""
band = self.height - FOOTER_BAND_PT
return len({round(l.top, 1) for l in self.lines if l.top >= band}) > 1
def is_indented(self, line: Line) -> bool:
return line.left > self.left_edge + INDENT_PT
def is_heading(self, line: Line) -> bool:
median = self.body_median_height
return bool(median) and line.height > median * HEADING_HEIGHT_RATIO
def largest_gap(self) -> tuple[float, float]:
"""Largest top-to-top distance between body lines, and where it starts.
Measured top-to-top rather than bottom-to-top, so a tall line inflates the gap
by its own height (a 160pt void under a heading reads as ~174pt). That errs
toward over-detection, which is the right direction for a check whose job is
to stop a hole from shipping.
"""
tops = sorted({round(l.top, 1) for l in self.body})
if len(tops) < 2:
return (0.0, 0.0)
return max((tops[i + 1] - tops[i], tops[i]) for i in range(len(tops) - 1))
def parse_pdf(path: Path) -> list[Page]:
if not shutil.which("pdftotext"):
raise RuntimeError("pdftotext (Poppler) not found; install poppler-utils")
try:
out = subprocess.run(
["pdftotext", "-bbox", "-enc", "UTF-8", str(path), "-"],
capture_output=True,
text=True,
# pdftotext emits UTF-8; without this Windows decodes it as cp1252 and
# a non-ASCII glyph in the CV crashes the run (same fix as verify_pdf.py).
encoding="utf-8",
errors="replace",
check=True,
).stdout
except subprocess.CalledProcessError as exc:
# A broken extractor has two distinct causes, not one: an xpdf-based pdftotext
# has no -bbox at all and exits 99 (Git for Windows puts one ahead of Poppler
# in PATH); a real Poppler before 26.05 aborts -bbox on a PDF whose Info dict
# has an empty string in any field - which hyperref writes for every field it
# does not set, so a lualatex/pdflatex document with hyperref and no pdftitle
# triggers this even with a working Poppler (#451). Either way this is a
# broken extractor, not a broken document, so it degrades to the skip path
# instead of exit 1.
stderr_lines = (exc.stderr or "").strip().splitlines()
detail = stderr_lines[0] if stderr_lines else f"exit {exc.returncode}"
raise RuntimeError(
f"pdftotext could not produce bounding boxes for {path} ({detail}); "
"either the pdftotext first in PATH is an xpdf build with no -bbox flag "
"(Git for Windows ships one ahead of Poppler), or Poppler aborted on this "
"document - Poppler 26.0x before 26.05 aborts on a PDF whose Info "
"dictionary carries an empty string, as hyperref writes when pdftitle is unset"
) from exc
pages = []
for _w, h, body in PAGE_RE.findall(out):
buckets: dict[float, list[tuple[float, float, float, str]]] = {}
for x_min, y_min, y_max, text in WORD_RE.findall(body):
key = round(float(y_min), 0) # words on one line share a rounded yMin
buckets.setdefault(key, []).append((float(x_min), float(y_min), float(y_max), text))
lines = [
Line(
top=min(w[1] for w in words),
bottom=max(w[2] for w in words),
left=min(w[0] for w in words),
height=max(w[2] - w[1] for w in words),
text=" ".join(w[3] for w in sorted(words)),
)
for words in buckets.values()
]
pages.append(Page(float(h), lines))
return pages
def find_orphans(pages: list[Page]) -> list[str]:
"""A page ending on an entry header or section heading whose content resumes overleaf.
Two shapes, both documented failures:
* the last body line of a page is a section heading (stranded heading)
* the last body lines are un-indented (an entry header) while the next page opens
with indented bullet lines, i.e. the entry was split across the break
"""
problems = []
# Indentation must be judged against the document's left margin, not each page's own
# minimum: a page that *opens* with indented bullets would otherwise treat their
# indent as its margin and report nothing.
body_lines = [l for p in pages for l in p.body]
if not body_lines:
return problems
doc_left = min(l.left for l in body_lines)
def indented(line: Line) -> bool:
return line.left > doc_left + INDENT_PT
for i in range(len(pages) - 1):
here, nxt = pages[i], pages[i + 1]
if here.empty or nxt.empty:
continue
last, first = here.body[-1], nxt.body[0]
if here.is_heading(last):
problems.append(
f"p{i + 1} ends on the section heading {last.text.strip()!r} with its content "
f"on p{i + 2}. Shorten the entry that follows it, or let the heading and its "
"first entry move to the next page together"
)
elif not indented(last) and indented(first):
# moderncv puts an itemize marker in its own bbox line at the list's left
# edge, so a list item split across the break looks like an un-indented
# header followed by indented text. Different defect, different fix.
if not re.search(r"\w", last.text):
problems.append(
f"p{i + 1} ends on a lone list marker whose text continues on p{i + 2} "
f"({first.text.strip()[:60]!r}): a bullet is split across the page break. "
"Shorten the preceding content so the whole item fits on one page"
)
else:
problems.append(
f"p{i + 1} ends on the un-indented line {last.text.strip()[:60]!r} while "
f"p{i + 2} opens with the indented line {first.text.strip()[:60]!r}: an entry "
"header is orphaned from its bullets. Add \\needspace before that "
"\\cventry, or shorten it"
)
return problems
def report(path: Path, pages: list[Page]) -> list[str]:
problems: list[str] = []
print(f"{path}: {len(pages)} page(s) (page count is verify_pdf.py's job, not checked here)")
for i, page in enumerate(pages, 1):
if page.empty:
problems.append(f"p{i} contains no text")
print(f" p{i}: EMPTY")
continue
gap, gap_y = page.largest_gap()
share = page.bottom_space / page.height
print(
f" p{i}: text y {page.body[0].top:.0f}..{page.body[-1].bottom:.0f}"
f" of {page.height:.0f}pt | bottom {page.bottom_space:.0f}pt ({share * 100:.0f}%)"
f" | largest gap {gap:.0f}pt at y{gap_y:.0f}"
)
if gap > GAP_LIMIT_PT:
problems.append(
f"p{i} has a {gap:.0f}pt hole at y{gap_y:.0f} (~{gap / 14:.0f} blank lines). "
"A moderncv \\cventry is an unbreakable tabular: shorten the entry that "
"follows the hole so it fits, or move a shorter section above it"
)
if i < len(pages) and share > BOTTOM_LIMIT_FRACTION:
problems.append(
f"p{i} ends {page.bottom_space:.0f}pt ({share * 100:.0f}%) early although "
"more pages follow, which reads as a broken page break"
)
if page.footer_crowded:
problems.append(
f"p{i} has body text inside the bottom margin band, colliding with the "
"footer; stop stretching the page with \\enlargethispage and cut content"
)
if i == len(pages) > 1 and share > LAST_PAGE_THIN_FRACTION:
problems.append(
f"p{i} is the last page and {share * 100:.0f}% empty, which reads as an "
"unfinished document; restore the highest-relevance content previously cut"
)
problems.extend(find_orphans(pages))
return problems
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("pdf", nargs="?", type=Path)
args = ap.parse_args()
if not args.pdf:
ap.error("pdf is required")
if not args.pdf.exists():
print(f"error: {args.pdf} not found", file=sys.stderr)
return 2
try:
pages = parse_pdf(args.pdf)
except RuntimeError as exc:
print(f"skipped: {exc}", file=sys.stderr)
return 2
problems = report(args.pdf, pages)
if problems:
print("\nLAYOUT PROBLEMS:")
for m in problems:
print(f" - {m}")
return 1
print("layout: clean")
return 0
if __name__ == "__main__":
sys.exit(main())
+38 -1
View File
@@ -4,12 +4,18 @@
Text-layer extraction tries pypdf (BSD, optional `pip install pypdf`) first, Text-layer extraction tries pypdf (BSD, optional `pip install pypdf`) first,
then Poppler `pdftotext` if pypdf is missing, raises, or returns zero then Poppler `pdftotext` if pypdf is missing, raises, or returns zero
extractable characters. Poppler remains the fallback. extractable characters. Poppler remains the fallback.
`--contains` compares after `normalize_text()` has folded both sides: whitespace,
Unicode normalization form (NFC), and the typographic substitutions LaTeX makes to
the source text. The fold is comparison-time only - the `--dump-text` output stays
the raw text layer an ATS parser actually sees.
""" """
import argparse import argparse
import re import re
import subprocess import subprocess
import sys import sys
import unicodedata
from pathlib import Path from pathlib import Path
@@ -47,7 +53,34 @@ def parse_page_count(pdfinfo_output):
return int(match.group(1)) return int(match.group(1))
# Typographic substitutions the moderncv/cover.cls templates produce from plain
# source text, mapped back to what a user types into --contains. LaTeX ligatures
# ' into U+2019 and -- into U+2013, so "Master's degree" and "2016-2024" are
# absent from the text layer of a CV that plainly contains them (#385). Applied
# to both sides of the comparison; the extracted dump is never rewritten.
TYPOGRAPHIC_FOLDS = str.maketrans(
{
"\u2018": "'", # ` -> quoteleft
"\u2019": "'", # ' -> quoteright (the possessive apostrophe)
"\u201c": '"', # `` -> quotedblleft
"\u201d": '"', # '' -> quotedblright
"\u2013": "-", # -- -> endash (the \cventry date-range case)
"\u2014": "-", # --- -> emdash
"\u00a0": " ", # ~ -> no-break space
}
)
def normalize_text(text): def normalize_text(text):
"""Fold a string for comparison: NFC, typographic punctuation, whitespace.
NFC covers the pdflatex text layer, which without T1 font encoding stores
accented letters decomposed (`e` + U+0300) while a user types them
precomposed (U+00E8); both forms fold to the same string (#384). The fold
applies to what is compared, never to what is dumped: the date-range rule in
`05-cv-templates.md` still needs the raw en-dash visible in `--dump-text`.
"""
text = unicodedata.normalize("NFC", text).translate(TYPOGRAPHIC_FOLDS)
return " ".join(text.split()) return " ".join(text.split())
@@ -144,7 +177,11 @@ def build_parser():
"--contains", "--contains",
action="append", action="append",
default=[], default=[],
help="text that must appear after whitespace normalization; repeatable", help=(
"text that must appear in the text layer; both sides are folded for "
"whitespace, NFC, and LaTeX's typographic substitutions (curly "
"apostrophes/quotes, en/em dashes, no-break spaces); repeatable"
),
) )
parser.add_argument( parser.add_argument(
"--dump-text", "--dump-text",