@kinloom/cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,553 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "click>=8.1",
6
+ # "httpx>=0.27",
7
+ # ]
8
+ # ///
9
+ """Search Library of Congress Chronicling America historic newspapers.
10
+
11
+ Uses the public loc.gov JSON API (no key, no account). The retired
12
+ chroniclingamerica.loc.gov search API now 308-redirects away; do not use it
13
+ or third-party docs that describe it.
14
+
15
+ loc.gov collection searches are slow on the server side: measured
16
+ 2026-11-25, connect + TLS took < 0.1 s but time-to-first-byte was 19-43 s
17
+ for every search (with or without q, dates, state, dl, at). The default
18
+ timeout budget is therefore 120 s, and every successful search is cached on
19
+ disk so a repeat never hits loc.gov again.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import math
27
+ import os
28
+ import re
29
+ import sys
30
+ import time
31
+ from contextlib import contextmanager
32
+ from pathlib import Path
33
+ from typing import Any, Iterator
34
+ from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
35
+
36
+ import click
37
+ import httpx
38
+
39
+ COLLECTION_BASE = "https://www.loc.gov/collections/chronicling-america/"
40
+ HEADERS = {
41
+ "User-Agent": "kinloom/1.0 (genealogy research)",
42
+ "Accept": "application/json",
43
+ }
44
+ # tile.loc.gov (storage-services PDFs) rejects hotlinking: it requires a
45
+ # loc.gov Referer. Send one for all file downloads; harmless elsewhere.
46
+ DOWNLOAD_HEADERS = dict(HEADERS, Referer="https://www.loc.gov/")
47
+ # Measured 2026-11-25: loc.gov search TTFB is 19-43 s. An 8 s budget made
48
+ # 80%+ of searches fail. One probe under 6 parallel requests took 70 s,
49
+ # so 120 s covers the observed tail with headroom.
50
+ DEFAULT_TIMEOUT = 120.0
51
+ DOWNLOAD_TIMEOUT = 60.0
52
+ RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504, 520, 522, 524}
53
+ MAX_RETRY_AFTER_S = 30.0
54
+ COLLECTION_START_YEAR = "1736"
55
+ COLLECTION_END_YEAR = "1963"
56
+ DEFAULT_CACHE_TTL_HOURS = 168.0
57
+ CACHE_SCHEMA = 1
58
+
59
+ US_STATES = {
60
+ "AL": "alabama", "AK": "alaska", "AZ": "arizona", "AR": "arkansas",
61
+ "CA": "california", "CO": "colorado", "CT": "connecticut", "DE": "delaware",
62
+ "DC": "district of columbia", "FL": "florida", "GA": "georgia", "HI": "hawaii",
63
+ "ID": "idaho", "IL": "illinois", "IN": "indiana", "IA": "iowa", "KS": "kansas",
64
+ "KY": "kentucky", "LA": "louisiana", "ME": "maine", "MD": "maryland",
65
+ "MA": "massachusetts", "MI": "michigan", "MN": "minnesota", "MS": "mississippi",
66
+ "MO": "missouri", "MT": "montana", "NE": "nebraska", "NV": "nevada",
67
+ "NH": "new hampshire", "NJ": "new jersey", "NM": "new mexico", "NY": "new york",
68
+ "NC": "north carolina", "ND": "north dakota", "OH": "ohio", "OK": "oklahoma",
69
+ "OR": "oregon", "PA": "pennsylvania", "PR": "puerto rico", "RI": "rhode island",
70
+ "SC": "south carolina", "SD": "south dakota", "TN": "tennessee", "TX": "texas",
71
+ "UT": "utah", "VT": "vermont", "VA": "virginia", "VI": "virgin islands",
72
+ "WA": "washington", "WV": "west virginia", "WI": "wisconsin", "WY": "wyoming",
73
+ }
74
+
75
+
76
+ # --- disk cache ---------------------------------------------------------------
77
+
78
+ def cache_dir() -> Path:
79
+ override = os.environ.get("KINLOOM_CHRONAM_CACHE_DIR")
80
+ if override:
81
+ return Path(override).expanduser()
82
+ return Path.home() / ".cache" / "kinloom-chronam"
83
+
84
+
85
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
86
+ if cli_ttl is not None:
87
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
88
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
89
+ return float(cli_ttl)
90
+ raw = os.environ.get("KINLOOM_CHRONAM_CACHE_TTL_HOURS")
91
+ if raw is not None and raw.strip():
92
+ try:
93
+ parsed = float(raw.strip())
94
+ except ValueError as exc:
95
+ raise click.BadParameter(f"Invalid KINLOOM_CHRONAM_CACHE_TTL_HOURS value: {raw!r}.") from exc
96
+ if not math.isfinite(parsed) or parsed < 0:
97
+ raise click.BadParameter(
98
+ f"Invalid KINLOOM_CHRONAM_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
99
+ return parsed
100
+ return DEFAULT_CACHE_TTL_HOURS
101
+
102
+
103
+ @contextmanager
104
+ def file_lock(lock_path: Path) -> Iterator[None]:
105
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
106
+ try:
107
+ import fcntl
108
+ except ImportError:
109
+ yield
110
+ return
111
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
112
+ with open(lock_path, "a+b") as lock_file:
113
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
114
+ try:
115
+ yield
116
+ finally:
117
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
118
+
119
+
120
+ def atomic_write_json(dest: Path, payload: Any) -> None:
121
+ dest.parent.mkdir(parents=True, exist_ok=True)
122
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
123
+ try:
124
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
125
+ os.replace(tmp, dest)
126
+ except Exception:
127
+ tmp.unlink(missing_ok=True)
128
+ raise
129
+
130
+
131
+ def cache_key(url: str, params: list[tuple[str, str]] | None) -> str:
132
+ canonical = json.dumps([url, sorted(params or [])], separators=(",", ":"))
133
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
134
+
135
+
136
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
137
+ if not path.is_file():
138
+ return None
139
+ try:
140
+ entry = json.loads(path.read_text(encoding="utf-8"))
141
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
142
+ return None
143
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
144
+ return None
145
+ fetched = entry.get("fetched_at")
146
+ if not isinstance(fetched, (int, float)):
147
+ return None
148
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
149
+ return None
150
+ data = entry.get("data")
151
+ return data if isinstance(data, dict) else None
152
+
153
+
154
+ def cached_get_json(
155
+ url: str,
156
+ params: list[tuple[str, str]] | None,
157
+ *,
158
+ timeout: float,
159
+ refresh: bool,
160
+ ttl_hours: float,
161
+ cacheable=lambda data: True,
162
+ ) -> tuple[dict, bool]:
163
+ """Return (data, cache_hit). Concurrent callers of one query serialize on
164
+ a per-key flock, so the second caller reads the first caller's result."""
165
+ key = cache_key(url, params)
166
+ root = cache_dir()
167
+ path = root / f"{key}.json"
168
+ if not refresh:
169
+ hit = read_cache(path, ttl_hours)
170
+ if hit is not None:
171
+ return hit, True
172
+ with file_lock(root / f"{key}.lock"):
173
+ if not refresh:
174
+ hit = read_cache(path, ttl_hours)
175
+ if hit is not None:
176
+ return hit, True
177
+ data = _get_json(url, params=params, timeout=timeout)
178
+ if cacheable(data):
179
+ atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
180
+ "url": url, "params": params or [], "data": data})
181
+ return data, False
182
+
183
+
184
+ # --- HTTP -----------------------------------------------------------------------
185
+
186
+ def _retry_after_seconds(resp: httpx.Response) -> float:
187
+ raw = resp.headers.get("retry-after", "").strip()
188
+ try:
189
+ return max(0.0, min(float(raw), MAX_RETRY_AFTER_S))
190
+ except ValueError:
191
+ return 1.0
192
+
193
+
194
+ def _get_json(
195
+ url: str,
196
+ params: dict | list[tuple[str, str]] | None = None,
197
+ *,
198
+ timeout: float = DEFAULT_TIMEOUT,
199
+ client: httpx.Client | None = None,
200
+ ) -> dict:
201
+ deadline = time.monotonic() + timeout
202
+ last_exc: Exception | None = None
203
+
204
+ def _run(http_client: httpx.Client) -> dict:
205
+ nonlocal last_exc
206
+ for attempt in range(2):
207
+ remaining = deadline - time.monotonic()
208
+ if remaining <= 0.25:
209
+ break
210
+ try:
211
+ resp = http_client.get(url, params=params, timeout=remaining)
212
+ except httpx.TimeoutException as exc:
213
+ raise click.ClickException(
214
+ f"loc.gov request timed out after {timeout:.1f}s ({exc}). "
215
+ "loc.gov searches normally take 20-45 s; increase --timeout, "
216
+ "narrow with --state, --dates, or --lccn, "
217
+ "or open the browser URL from `chronam url`."
218
+ ) from exc
219
+ except (httpx.RemoteProtocolError, httpx.ConnectError) as exc:
220
+ last_exc = exc
221
+ if attempt == 0 and (deadline - time.monotonic()) >= 2.0:
222
+ time.sleep(0.4)
223
+ continue
224
+ raise click.ClickException(
225
+ f"loc.gov connection error: {exc}. "
226
+ "Retry once or narrow with --state/--dates/--lccn."
227
+ ) from exc
228
+ except httpx.HTTPError as exc:
229
+ raise click.ClickException(f"loc.gov request failed: {exc}") from exc
230
+
231
+ if resp.status_code in RETRYABLE_STATUS_CODES:
232
+ last_exc = httpx.HTTPStatusError(
233
+ f"HTTP {resp.status_code}", request=resp.request, response=resp
234
+ )
235
+ wait = _retry_after_seconds(resp) if resp.status_code in (429, 503) else 0.4
236
+ if attempt == 0 and (deadline - time.monotonic()) >= wait + 2.0:
237
+ time.sleep(wait)
238
+ continue
239
+ kind = "rate limited" if resp.status_code == 429 else "transient service error"
240
+ raise click.ClickException(
241
+ f"loc.gov returned HTTP {resp.status_code} ({kind}). "
242
+ "Wait and retry, narrow with --state/--dates/--lccn, or open `chronam url` in a browser."
243
+ )
244
+
245
+ try:
246
+ resp.raise_for_status()
247
+ except httpx.HTTPStatusError as exc:
248
+ raise click.ClickException(
249
+ f"loc.gov returned HTTP {resp.status_code} for {resp.request.url}"
250
+ ) from exc
251
+
252
+ try:
253
+ return resp.json()
254
+ except ValueError as exc:
255
+ raise click.ClickException(
256
+ f"loc.gov returned non-JSON response (HTTP {resp.status_code}, "
257
+ f"content-type={resp.headers.get('content-type', 'unknown')})."
258
+ ) from exc
259
+
260
+ raise click.ClickException(
261
+ f"loc.gov request failed after {timeout:.1f}s: {last_exc}"
262
+ )
263
+
264
+ if client is not None:
265
+ return _run(client)
266
+ with httpx.Client(headers=HEADERS, timeout=timeout, follow_redirects=True) as managed_client:
267
+ return _run(managed_client)
268
+
269
+
270
+ # --- query building ----------------------------------------------------------
271
+
272
+ def _resolve_query(words: tuple[str, ...], terms_opt: str | None) -> str:
273
+ query = " ".join(w for w in words if w).strip() or (terms_opt or "").strip()
274
+ if not query:
275
+ raise click.UsageError("Provide QUERY words as positional arguments or via --terms/--query.")
276
+ return query
277
+
278
+
279
+ def _resolve_dates(dates: str | None, date_from: str | None, date_to: str | None) -> str | None:
280
+ if dates:
281
+ cleaned = dates.strip().replace("-", "/")
282
+ if re.fullmatch(r"\d{4}", cleaned):
283
+ return f"{cleaned}/{cleaned}"
284
+ if not re.fullmatch(r"\d{4}/\d{4}", cleaned):
285
+ raise click.BadParameter(f"--dates {dates!r}: expected YYYY/YYYY (or YYYY).", param_hint="--dates")
286
+ return cleaned
287
+ if date_from or date_to:
288
+ start = (date_from or COLLECTION_START_YEAR).strip()[:4]
289
+ end = (date_to or COLLECTION_END_YEAR).strip()[:4]
290
+ for label, year in (("start", start), ("end", end)):
291
+ if not re.fullmatch(r"\d{4}", year):
292
+ raise click.BadParameter(f"{label} year {year!r}: expected YYYY.")
293
+ return f"{start}/{end}"
294
+ return None
295
+
296
+
297
+ def normalize_state(state: str) -> str:
298
+ cleaned = state.strip()
299
+ return US_STATES.get(cleaned.upper(), cleaned).lower()
300
+
301
+
302
+ def build_search_params(query: str, *, dates: str | None, level: str, limit: int, page: int,
303
+ state: str | None, lccn: str | None) -> list[tuple[str, str]]:
304
+ params: list[tuple[str, str]] = [
305
+ ("q", query),
306
+ ("fo", "json"),
307
+ ("at", "search,results"),
308
+ ("c", str(limit)),
309
+ ("sp", str(page)),
310
+ ]
311
+ if level != "all":
312
+ params.append(("dl", level))
313
+ if dates:
314
+ params.append(("dates", dates))
315
+ if state:
316
+ params.append(("fa", f"location_state:{normalize_state(state)}"))
317
+ if lccn:
318
+ params.append(("fa", f"number_lccn:{lccn.strip()}"))
319
+ return params
320
+
321
+
322
+ def _first(value):
323
+ if isinstance(value, list):
324
+ return value[0] if value else None
325
+ return value
326
+
327
+
328
+ def _compact_result(item: dict) -> dict:
329
+ return {
330
+ "title": _first(item.get("partof_title")) or item.get("title"),
331
+ "date": item.get("date"),
332
+ "state": _first(item.get("location_state")),
333
+ "county": _first(item.get("location_county")),
334
+ "city": _first(item.get("location_city")),
335
+ "lccn": item.get("number_lccn"),
336
+ "page": item.get("number_page"),
337
+ "url": item.get("url"),
338
+ "id": item.get("id"),
339
+ }
340
+
341
+
342
+ def _print_search(data: dict, as_json: bool, cache_hit: bool) -> None:
343
+ search = data.get("search") or {}
344
+ hits = search.get("hits")
345
+ results = data.get("results") or []
346
+ if as_json:
347
+ click.echo(json.dumps(
348
+ {"hits": hits, "cache_hit": cache_hit, "results": [_compact_result(r) for r in results]},
349
+ indent=2, ensure_ascii=False))
350
+ return
351
+ click.echo(f"hits: {hits} (showing {len(results)} on this page){' [cache]' if cache_hit else ''}")
352
+ for item in results:
353
+ c = _compact_result(item)
354
+ click.echo(f"- {c['date']} | {c['title']} | {c['state']} | {c['url']}")
355
+
356
+
357
+ def _search_cacheable(data: dict) -> bool:
358
+ # loc.gov sometimes answers a valid query with a transient 0-hit page
359
+ # (measured 2026-11-25: "Abraham Lincoln" gave 0, then 25,392 on rerun).
360
+ # Never cache an empty answer, so the next call asks loc.gov again.
361
+ hits = (data.get("search") or {}).get("hits")
362
+ return bool(hits) and bool(data.get("results"))
363
+
364
+
365
+ def _resource_url_json(resource_url: str) -> str:
366
+ parsed = urlparse(resource_url)
367
+ qs = parse_qs(parsed.query)
368
+ qs["fo"] = ["json"]
369
+ return urlunparse(parsed._replace(query=urlencode(qs, doseq=True)))
370
+
371
+
372
+ def _build_resource_url(lccn: str, date: str, edition: str, seq: str) -> str:
373
+ return f"https://www.loc.gov/resource/{lccn}/{date}/ed-{edition}/?sp={seq}"
374
+
375
+
376
+ def _cache_options(f):
377
+ f = click.option("--cache-ttl-hours", type=float, default=None,
378
+ help=f"Cache TTL in hours (default {DEFAULT_CACHE_TTL_HOURS:g}; "
379
+ "env KINLOOM_CHRONAM_CACHE_TTL_HOURS).")(f)
380
+ f = click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query loc.gov.")(f)
381
+ return f
382
+
383
+
384
+ def _query_options(f):
385
+ for decorator in reversed([
386
+ click.argument("query", nargs=-1),
387
+ click.option("--terms", "--query", "-q", "terms_opt", default=None,
388
+ help="Alias for positional QUERY."),
389
+ click.option("--dates", default=None, help="Date range YYYY/YYYY (or one year YYYY)."),
390
+ click.option("--date-from", "--from-year", "--date1", "--year1", "--start", "date_from",
391
+ default=None, help="Start year YYYY (alternative to --dates)."),
392
+ click.option("--date-to", "--to-year", "--date2", "--year2", "--end", "date_to",
393
+ default=None, help="End year YYYY (alternative to --dates)."),
394
+ click.option("--level", default="page", type=click.Choice(["page", "issue", "title", "all"]),
395
+ show_default=True, help="Display level (dl=)."),
396
+ click.option("--state", default=None,
397
+ help="State name or postal code (CA, NJ); sent as fa=location_state:<state>."),
398
+ click.option("--lccn", default=None, help="Filter by newspaper LCCN via fa=number_lccn:<lccn>."),
399
+ ]):
400
+ f = decorator(f)
401
+ return f
402
+
403
+
404
+ @click.group()
405
+ def cli() -> None:
406
+ """Search Chronicling America historic newspapers (Library of Congress)."""
407
+
408
+
409
+ @cli.command()
410
+ @_query_options
411
+ @click.option("--limit", "--per-page", "--rows", "-n", default=10, show_default=True,
412
+ help="Results per page (c=).")
413
+ @click.option("--page", "-p", default=1, show_default=True, help="Results page (sp=).")
414
+ @click.option("--timeout", default=DEFAULT_TIMEOUT, show_default=True, type=float,
415
+ help="Request timeout budget in seconds (loc.gov search takes 20-45 s).")
416
+ @_cache_options
417
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of compact text.")
418
+ def search(query, terms_opt, dates, date_from, date_to, level, state, lccn, limit, page,
419
+ timeout, refresh, cache_ttl_hours, as_json):
420
+ """Search newspaper pages for QUERY (full-text, e.g. a surname).
421
+
422
+ Multi-word queries need no quotes: `chronam search Abraham Lincoln`.
423
+ Results are cached on disk (~/.cache/kinloom-chronam, 168 h TTL).
424
+ """
425
+ resolved_query = _resolve_query(query, terms_opt)
426
+ params = build_search_params(resolved_query, dates=_resolve_dates(dates, date_from, date_to),
427
+ level=level, limit=limit, page=page, state=state, lccn=lccn)
428
+ ttl = resolve_ttl_hours(cache_ttl_hours)
429
+ data, cache_hit = cached_get_json(COLLECTION_BASE, params, timeout=timeout, refresh=refresh,
430
+ ttl_hours=ttl, cacheable=_search_cacheable)
431
+ results = data.get("results") or []
432
+ hits = (data.get("search") or {}).get("hits")
433
+ if hits and not results:
434
+ click.echo(
435
+ f"Warning: loc.gov reported {hits} total hits but returned 0 rows on page {page}. "
436
+ "Check --page or retry once if loc.gov dropped facet results.",
437
+ err=True,
438
+ )
439
+ elif not hits:
440
+ click.echo(
441
+ "Note: 0 hits. loc.gov sometimes returns a transient empty answer; empty results are "
442
+ "never cached, so one rerun confirms a true zero.",
443
+ err=True,
444
+ )
445
+ data["results"] = results
446
+ _print_search(data, as_json, cache_hit)
447
+
448
+
449
+ @cli.command()
450
+ @click.argument("resource_url", required=False)
451
+ @click.option("--lccn", default=None, help="Newspaper LCCN, e.g. sn83045462.")
452
+ @click.option("--date", default=None, help="Issue date YYYY-MM-DD.")
453
+ @click.option("--edition", default="1", show_default=True)
454
+ @click.option("--seq", default="1", show_default=True, help="Page sequence within the issue (?sp=).")
455
+ @click.option("--timeout", default=DEFAULT_TIMEOUT, show_default=True, type=float,
456
+ help="Request timeout budget in seconds.")
457
+ @_cache_options
458
+ @click.option("--json", "as_json", is_flag=True, help="Emit the raw item JSON.")
459
+ def get(resource_url, lccn, date, edition, seq, timeout, refresh, cache_ttl_hours, as_json):
460
+ """Show metadata and download links for one newspaper page.
461
+
462
+ Give a loc.gov resource URL, or build one with --lccn --date [--edition --seq].
463
+ """
464
+ if resource_url is None:
465
+ if not lccn or not date:
466
+ raise click.UsageError("Give a resource URL or both --lccn and --date.")
467
+ resource_url = _build_resource_url(lccn, date, edition, seq)
468
+ data, _hit = cached_get_json(_resource_url_json(resource_url), None, timeout=timeout,
469
+ refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
470
+ if as_json:
471
+ click.echo(json.dumps(data, indent=2, ensure_ascii=False))
472
+ return
473
+ item = data.get("item") or {}
474
+ resource = data.get("resource") or {}
475
+ click.echo(f"title: {resource.get('title') or item.get('title')}")
476
+ click.echo(f"date: {item.get('date')}")
477
+ click.echo(f"lccn: {_first(item.get('number_lccn')) or item.get('lccn')}")
478
+ click.echo(f"place: {_first(item.get('location_city'))}, {_first(item.get('location_state'))}")
479
+ click.echo(f"url: {resource_url}")
480
+ for res in data.get("resources") or []:
481
+ for key in ("pdf", "image", "fulltext_file", "iiif_manifest_url"):
482
+ if res.get(key):
483
+ click.echo(f"{key}: {res[key]}")
484
+
485
+
486
+ @cli.command()
487
+ @click.argument("resource_url", required=False)
488
+ @click.option("--lccn", default=None)
489
+ @click.option("--date", default=None, help="Issue date YYYY-MM-DD.")
490
+ @click.option("--edition", default="1", show_default=True)
491
+ @click.option("--seq", default="1", show_default=True)
492
+ @click.option("--out", "--out-dir", "-o", "out", default=".", show_default=True, help="Output directory.")
493
+ @click.option("--pdf/--no-pdf", default=True, show_default=True, help="Download the page PDF.")
494
+ @click.option("--image/--no-image", default=False, show_default=True,
495
+ help="Download the IIIF image URL as served (reduced-size rendition).")
496
+ @click.option("--text/--no-text", default=False, show_default=True,
497
+ help="Download the ALTO XML word-coordinates file (OCR full text).")
498
+ @click.option("--timeout", default=DOWNLOAD_TIMEOUT, show_default=True, type=float,
499
+ help="Download timeout in seconds.")
500
+ @_cache_options
501
+ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text, timeout, refresh,
502
+ cache_ttl_hours):
503
+ """Download a newspaper page (PDF, image, OCR) plus metadata.json."""
504
+ if resource_url is None:
505
+ if not lccn or not date:
506
+ raise click.UsageError("Give a resource URL or both --lccn and --date.")
507
+ resource_url = _build_resource_url(lccn, date, edition, seq)
508
+ data, _hit = cached_get_json(_resource_url_json(resource_url), None, timeout=timeout,
509
+ refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
510
+ item = data.get("item") or {}
511
+ outdir = Path(out)
512
+ outdir.mkdir(parents=True, exist_ok=True)
513
+ stem = re.sub(r"[^A-Za-z0-9._-]+", "_",
514
+ f"{_first(item.get('number_lccn')) or 'loc'}_{item.get('date') or 'nodate'}_sp{seq}")
515
+ resources = (data.get("resources") or [{}])[0]
516
+ jobs = []
517
+ if pdf and resources.get("pdf"):
518
+ jobs.append(("pdf", resources["pdf"], f"{stem}.pdf"))
519
+ if image and resources.get("image"):
520
+ jobs.append(("image", resources["image"], f"{stem}.jpg"))
521
+ if text and resources.get("fulltext_file"):
522
+ jobs.append(("text", resources["fulltext_file"], f"{stem}.alto.xml"))
523
+ if not jobs:
524
+ click.echo("No downloadable resources found for this page.", err=True)
525
+ sys.exit(1)
526
+ with httpx.Client(headers=DOWNLOAD_HEADERS, timeout=timeout, follow_redirects=True) as client:
527
+ for kind, url, filename in jobs:
528
+ try:
529
+ resp = client.get(url)
530
+ resp.raise_for_status()
531
+ except httpx.HTTPError as exc:
532
+ raise click.ClickException(f"Failed downloading {kind} from {url}: {exc}") from exc
533
+ (outdir / filename).write_bytes(resp.content)
534
+ click.echo(f"{kind}: {outdir / filename} ({len(resp.content)} bytes)")
535
+ (outdir / f"{stem}.metadata.json").write_text(
536
+ json.dumps({"resource_url": resource_url, "item": item,
537
+ "resources": data.get("resources")}, indent=2, ensure_ascii=False))
538
+ click.echo(f"metadata: {outdir / (stem + '.metadata.json')}")
539
+
540
+
541
+ @cli.command()
542
+ @_query_options
543
+ def url(query, terms_opt, dates, date_from, date_to, level, state, lccn):
544
+ """Print the loc.gov website search URL for QUERY (open in a browser)."""
545
+ resolved_query = _resolve_query(query, terms_opt)
546
+ params = build_search_params(resolved_query, dates=_resolve_dates(dates, date_from, date_to),
547
+ level=level, limit=10, page=1, state=state, lccn=lccn)
548
+ browser = [(k, v) for k, v in params if k not in ("fo", "at", "c", "sp")]
549
+ click.echo(COLLECTION_BASE + "?" + urlencode(browser))
550
+
551
+
552
+ if __name__ == "__main__":
553
+ cli()
@@ -0,0 +1,53 @@
1
+ ---
2
+ name: cyndis-list
3
+ description: Use Cyndi's List, the free categorized directory of 332,000+ genealogy links, to find niche county-specific transcription sites (USGenWeb county pages, volunteer marriage indexes, church registers, cemetery surveys) across US states, counties, and international localities. Covers the category structure, stable URL patterns for US states and counties, the site search, and how to judge a linked site before citing it. Skill-only: there is no CLI, because Cyndi's List is a directory of links, not a records database. Use when you know the county and record type but not which volunteer site holds the transcription.
4
+ ---
5
+
6
+ # Cyndi's List
7
+
8
+ **Skill-only: no CLI.** Cyndi's List is a categorized directory of links, not a records database. There is no API, no search endpoint that returns records, and no stable result set to script against. A CLI would only re-print links a browser visit already shows. What this skill gives instead is the verified URL structure and a repeatable county-first workflow, so a researcher (or an agent with a browser) lands on the right category page in one step.
9
+
10
+ ## What it is
11
+
12
+ - Cyndi's List of Genealogy Sites on the Internet, `https://www.cyndislist.com/`, maintained by Cyndi Howells for more than 25 years. Free for everyone, no account.
13
+ - Roughly 332,000 links in 200+ categories, cross-referenced. Submitters write their own descriptions; Cyndi categorizes them. The waiting list for uncategorized submissions has historically run years, so the newest volunteer sites may not be listed yet.
14
+ - Think card catalog, not library: every entry points somewhere else. The value is discovery of small volunteer sites a search engine buries, especially USGenWeb county pages, local society transcription projects, and personal home pages.
15
+
16
+ ## Structure (verified live 2026-11-24)
17
+
18
+ - **Categories index:** `https://www.cyndislist.com/categories` lists every category with stable slug URLs (`/cemeteries/`, `/marriages/`, `/census-worldwide/`, `/surnames/`, `/maps/`, `/newspapers/`, `/obituaries/`, `/land/`, and more).
19
+ - **Top-level divisions:** Localities (by country, then state/province, then county), Records (by type: births, marriages, deaths, cemeteries, census, land, military, newspapers, obituaries), Religions, Ethnic Groups, Occupations, Research Tools, and more.
20
+ - **United States index:** `https://www.cyndislist.com/us/` with a page per state, e.g. Michigan at `https://www.cyndislist.com/us/mi/` or Illinois at `https://www.cyndislist.com/us/il/`.
21
+ - **State pages** split into record-type subpages: `/us/<st>/bmd/`, `/us/<st>/cemeteries/`, `/us/<st>/census/`, `/us/<st>/counties/`, `/us/<st>/directories/`, `/us/<st>/history/`, `/us/<st>/land/`, `/us/<st>/libraries/`, `/us/<st>/maps/`, `/us/<st>/military/`, `/us/<st>/newspapers/`, `/us/<st>/obituaries/`, `/us/<st>/periodicals/`, `/us/<st>/photos/`, and others.
22
+ - **County pages** follow one pattern: `https://www.cyndislist.com/us/<st>/counties/<county>/`, e.g. `https://www.cyndislist.com/us/mi/counties/wayne/`. Each county page links to topic subpages such as `bmd/`, `cemeteries/`, `census/`, `general/`. The counties index for a state lives at `https://www.cyndislist.com/us/<st>/counties/`.
23
+ - **Site search:** the search box is a Google Custom Search (Google CSE) over cyndislist.com, not a native index. It finds category pages and link descriptions, not the contents of linked sites. Prefer navigating the category tree over searching when you know the county and record type.
24
+
25
+ ## County-first workflow
26
+
27
+ 1. Start at the county page, not the homepage: `https://www.cyndislist.com/us/<st>/counties/<county>/` (using the two-letter state code and lowercase county name with no spaces, e.g. `/us/il/counties/sangamon/` or `/us/ny/counties/monroe/`). Verify the county page exists before citing it, since county coverage varies by state.
28
+ 2. On the county page, open the topic subpage matching the record you need: `bmd` for births/marriages/deaths, `cemeteries` for cemetery surveys and tombstone transcriptions, `census` for census transcriptions and indexes, `general` for the county's USGenWeb page and society sites.
29
+ 3. If the county page is thin, step up to the state record-type page (e.g. `/us/<st>/cemeteries/`) and to the national record-type category (e.g. `/cemeteries/`, `/marriages/`), which list statewide and national transcription projects that cover the county.
30
+ 4. For surname-specific sites, check `/surnames/`; for church registers, check the religion categories (`/catholic/`, `/baptist/`, `/methodist/`, `/quaker/`, and others).
31
+
32
+ ## Judging a linked site before citing it
33
+
34
+ Cyndi's List does not vet the contents of linked sites, and links rot. Before citing anything found through it:
35
+
36
+ - Open the link and confirm it still resolves and the transcription is actually there; dead or hijacked links are common on a directory this old.
37
+ - Note who transcribed it, from what source, and when. A volunteer transcription is a finding aid, not a primary source; cite the transcription as a pointer and verify against the original record (county clerk, FamilySearch image, or archive) before recording it as fact in `data/`.
38
+ - Prefer links to USGenWeb county pages, county genealogical societies, and library digital collections over undated personal home pages with no source notes.
39
+ - If a link is dead, try the Wayback Machine for the URL, then search the county name plus the record type; the project often moved to a new host.
40
+
41
+ ## What Cyndi's List cannot do
42
+
43
+ - It holds no records itself. Searching it for a surname finds pages that mention that surname in a link description, not individuals in records.
44
+ - It has no API and no bulk data download. Do not scrape it wholesale; it is one person's curated directory, and heavy crawling is poor citizenship toward the maintainer.
45
+ - Coverage is uneven: a county with an active USGenWeb volunteer has a rich page; a county without one may have almost nothing. An empty county page means "nothing catalogued here", not "no records exist".
46
+
47
+ ## Why there is no CLI
48
+
49
+ A CLI needs a machine interface: a public API, a stable search URL pattern returning records, or downloadable data. Cyndi's List has none of these. Its pages are hand-curated HTML link lists behind a Google Custom Search box, and the useful output (a handful of links on a county topic page) is read once by a human in a browser. Shipping a CLI that fetches and prints those links would add a tool that saves no work over opening the page, and it would go stale the moment Cyndi recategorizes a page. Skill-only is the honest shape.
50
+
51
+ ## Verified-live note
52
+
53
+ Homepage, categories index, state pages, counties index, and county topic subpages (`bmd`, `cemeteries`, `census`, and `general`) were verified live returning HTTP 200 on 2026-11-24.