@kinloom/cli 0.1.0 → 0.2.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 (102) hide show
  1. package/dist/assets/cached-ocr.py +556 -0
  2. package/dist/assets/ocr.md +52 -0
  3. package/dist/assets/prep-scan.md +59 -0
  4. package/dist/assets/prep-scan.py +891 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +129 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +120 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +116 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -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 +118 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +148 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +383 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.js +1 -1
  49. package/dist/commands/init.js +3 -3
  50. package/dist/commands/ops/audit.d.ts +138 -0
  51. package/dist/commands/ops/audit.d.ts.map +1 -0
  52. package/dist/commands/ops/audit.js +867 -0
  53. package/dist/commands/ops/audit.js.map +1 -0
  54. package/dist/commands/ops/context.d.ts +100 -0
  55. package/dist/commands/ops/context.d.ts.map +1 -0
  56. package/dist/commands/ops/context.js +917 -0
  57. package/dist/commands/ops/context.js.map +1 -0
  58. package/dist/commands/ops/help.d.ts +6 -0
  59. package/dist/commands/ops/help.d.ts.map +1 -0
  60. package/dist/commands/ops/help.js +74 -0
  61. package/dist/commands/ops/help.js.map +1 -0
  62. package/dist/commands/ops/index.d.ts +6 -0
  63. package/dist/commands/ops/index.d.ts.map +1 -0
  64. package/dist/commands/ops/index.js +6 -0
  65. package/dist/commands/ops/index.js.map +1 -0
  66. package/dist/commands/ops/integrate.d.ts +56 -0
  67. package/dist/commands/ops/integrate.d.ts.map +1 -0
  68. package/dist/commands/ops/integrate.js +872 -0
  69. package/dist/commands/ops/integrate.js.map +1 -0
  70. package/dist/commands/ops/sync.d.ts +177 -0
  71. package/dist/commands/ops/sync.d.ts.map +1 -0
  72. package/dist/commands/ops/sync.js +1078 -0
  73. package/dist/commands/ops/sync.js.map +1 -0
  74. package/dist/commands/ops/telemetry.d.ts +79 -0
  75. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  76. package/dist/commands/ops/telemetry.js +249 -0
  77. package/dist/commands/ops/telemetry.js.map +1 -0
  78. package/dist/commands/records/help.d.ts +18 -0
  79. package/dist/commands/records/help.d.ts.map +1 -0
  80. package/dist/commands/records/help.js +174 -0
  81. package/dist/commands/records/help.js.map +1 -0
  82. package/dist/commands/records/index.d.ts +5 -0
  83. package/dist/commands/records/index.d.ts.map +1 -0
  84. package/dist/commands/records/index.js +5 -0
  85. package/dist/commands/records/index.js.map +1 -0
  86. package/dist/commands/records/registry.d.ts +32 -0
  87. package/dist/commands/records/registry.d.ts.map +1 -0
  88. package/dist/commands/records/registry.js +227 -0
  89. package/dist/commands/records/registry.js.map +1 -0
  90. package/dist/commands/records/resolve.d.ts +14 -0
  91. package/dist/commands/records/resolve.d.ts.map +1 -0
  92. package/dist/commands/records/resolve.js +61 -0
  93. package/dist/commands/records/resolve.js.map +1 -0
  94. package/dist/commands/records/runner.d.ts +25 -0
  95. package/dist/commands/records/runner.d.ts.map +1 -0
  96. package/dist/commands/records/runner.js +224 -0
  97. package/dist/commands/records/runner.js.map +1 -0
  98. package/dist/index.d.ts +2 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +2 -0
  101. package/dist/index.js.map +1 -1
  102. package/package.json +3 -3
@@ -0,0 +1,528 @@
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 the Missouri State Archives vital-records databases.
10
+
11
+ Machine interface verified live 2026-11-24: the two
12
+ s1.sos.mo.gov databases are plain HTML POST forms (no API, no login,
13
+ no key). A browser User-Agent is required: the default curl/httpx
14
+ User-Agent gets 403 from sos.mo.gov. Search results are paged
15
+ 50 per page in a cookie session; this CLI keeps one session per run
16
+ and follows the session pager links.
17
+
18
+ Databases:
19
+ Death Certificates 1910-1975 (with certificate images as PDF)
20
+ Birth and Death Records Database, Pre-1910 (abstracts + detail pages)
21
+
22
+ Missouri Digital Heritage itself has no verified machine interface:
23
+ its CONTENTdm dmwebservices endpoint returns 403 (Cloudflare) to
24
+ automated requests, and its Advanced Search (mdh.deepwebaccess.com) has no
25
+ verified GET search URL. Use the `mdh` command for the browser path.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import re
32
+ import sys
33
+ from html.parser import HTMLParser
34
+ from pathlib import Path
35
+ from urllib.parse import urljoin
36
+
37
+ import click
38
+ import httpx
39
+
40
+ BASE = "https://s1.sos.mo.gov"
41
+ DEATH_PAGE = BASE + "/records/Archives/ArchivesMvc/DeathCertificates/"
42
+ DEATH_POST = BASE + "/Records/Archives/ArchivesMvc/"
43
+ DEATH_RESULTS = BASE + "/Records/Archives/ArchivesMvc/DeathCertificates/Results"
44
+ PRE1910_PAGE = BASE + "/records/archives/ArchivesMVC/birthdeath/"
45
+ PRE1910_POST = BASE + "/Records/Archives/ArchivesMvc/BirthDeath"
46
+ PRE1910_RESULTS = BASE + "/Records/Archives/ArchivesMvc/birthdeath/Results"
47
+ PRE1910_DETAIL = BASE + "/records/archives/ArchivesMVC/birthdeath/Detail"
48
+ MDH_HOME = "https://www.sos.mo.gov/mdh"
49
+ MDH_SEARCH = "https://mdh.deepwebaccess.com/mdh/"
50
+ ARCHIVES_HOME = "https://www.sos.mo.gov/archives"
51
+ USER_AGENT = (
52
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
53
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
54
+ )
55
+ ALL_COUNTIES = "-- Search All --"
56
+ ALL_COUNTIES_PRE1910 = "-- All Counties --"
57
+ MATCH_METHODS = {
58
+ "contains": "Contains",
59
+ "starts-with": "StartsWith",
60
+ "ends-with": "EndsWith",
61
+ }
62
+
63
+
64
+ class _Cell:
65
+ __slots__ = ("text", "hrefs")
66
+
67
+ def __init__(self):
68
+ self.text = ""
69
+ self.hrefs = []
70
+
71
+
72
+ class _TableParser(HTMLParser):
73
+ """Collect every <table> as a list of rows of _Cell."""
74
+
75
+ def __init__(self):
76
+ super().__init__(convert_charrefs=True)
77
+ self.tables = []
78
+ self._table = None
79
+ self._row = None
80
+ self._cell = None
81
+
82
+ def handle_starttag(self, tag, attrs):
83
+ if tag == "table":
84
+ self._table = []
85
+ self.tables.append(self._table)
86
+ elif tag == "tr" and self._table is not None:
87
+ self._row = []
88
+ self._table.append(self._row)
89
+ elif tag in ("td", "th") and self._row is not None:
90
+ self._cell = _Cell()
91
+ self._row.append(self._cell)
92
+ elif tag == "a" and self._cell is not None:
93
+ href = dict(attrs).get("href")
94
+ if href:
95
+ self._cell.hrefs.append(href)
96
+ elif tag in ("br", "li", "p", "div") and self._cell is not None:
97
+ # Detail pages stack labels/values with <br/> and <li> and no
98
+ # whitespace; keep the pieces from running together.
99
+ self._cell.text += " "
100
+
101
+ def handle_endtag(self, tag):
102
+ if tag in ("td", "th"):
103
+ self._cell = None
104
+ elif tag == "tr":
105
+ self._row = None
106
+ elif tag == "table":
107
+ self._table = None
108
+
109
+ def handle_data(self, data):
110
+ if self._cell is not None:
111
+ self._cell.text += data
112
+
113
+
114
+ def _clean(text):
115
+ return " ".join(text.split())
116
+
117
+
118
+ def _parse_tables(html):
119
+ parser = _TableParser()
120
+ parser.feed(html)
121
+ return parser.tables
122
+
123
+
124
+ def _find_results_table(html, *header_markers):
125
+ for table in _parse_tables(html):
126
+ if not table:
127
+ continue
128
+ header = [_clean(c.text) for c in table[0]]
129
+ joined = " ".join(header)
130
+ if any(m in joined for m in header_markers):
131
+ return header, table[1:]
132
+ return None, []
133
+
134
+
135
+ def _total_results(html):
136
+ m = re.search(r"Showing records \d+ to \d+ of (\d+)", html)
137
+ return int(m.group(1)) if m else None
138
+
139
+
140
+ def _client():
141
+ return httpx.Client(
142
+ headers={"User-Agent": USER_AGENT},
143
+ follow_redirects=True,
144
+ timeout=60.0,
145
+ )
146
+
147
+
148
+ def _form_token(html):
149
+ m = re.search(r'name="__ncforminfo" value="([^"]+)"', html)
150
+ return m.group(1) if m else None
151
+
152
+
153
+ def _post_search(client, page_url, post_url, data):
154
+ """GET the form page first (cookies + anti-bot token), then POST."""
155
+ page = client.get(page_url)
156
+ page.raise_for_status()
157
+ token = _form_token(page.text)
158
+ if token:
159
+ data = dict(data)
160
+ data["__ncforminfo"] = token
161
+ resp = client.post(post_url, data=data)
162
+ resp.raise_for_status()
163
+ return resp.text
164
+
165
+
166
+ def _parse_death_name(text):
167
+ """Split 'Jane Doe - Deceased John Doe - Spouse ...' into roles.
168
+
169
+ For 1953-1975 certificates the name cell also lists spouse, father,
170
+ and mother. Returns a dict with at least 'name' (the deceased).
171
+ """
172
+ out = {}
173
+ parts = re.split(r"\s+-\s+(Deceased|Spouse|Father|Mother)\s*", _clean(text))
174
+ if not parts:
175
+ return out
176
+ # Each role label FOLLOWS the name it describes:
177
+ # "Jane Doe - Deceased John Doe - Spouse ..."
178
+ for i in range(1, len(parts), 2):
179
+ name = _clean(parts[i - 1])
180
+ if name:
181
+ out[parts[i].lower()] = name
182
+ if "deceased" in out:
183
+ out["name"] = out["deceased"]
184
+ elif parts:
185
+ out["name"] = _clean(parts[0])
186
+ return out
187
+
188
+
189
+ def _death_rows(html):
190
+ _header, rows = _find_results_table(html, "Date of Death")
191
+ out = []
192
+ for row in rows:
193
+ cells = [_clean(c.text) for c in row]
194
+ if len(cells) < 5 or not cells[0]:
195
+ continue
196
+ rec = _parse_death_name(cells[0])
197
+ rec["age"] = cells[1]
198
+ rec["date_of_death"] = cells[2]
199
+ rec["county"] = cells[3]
200
+ rec["cert"] = cells[4]
201
+ rec["ssn4"] = cells[5] if len(cells) > 5 else ""
202
+ img = row[6].hrefs[0] if len(row) > 6 and row[6].hrefs else ""
203
+ rec["image"] = urljoin(BASE, img) if img else ""
204
+ out.append(rec)
205
+ return out
206
+
207
+
208
+ def _pre1910_rows(html, kind):
209
+ if kind == "death":
210
+ _header, rows = _find_results_table(html, "Date Of Death")
211
+ else:
212
+ _header, rows = _find_results_table(html, "Date Of Birth")
213
+ out = []
214
+ for row in rows:
215
+ cells = [_clean(c.text) for c in row]
216
+ if not cells or not cells[0]:
217
+ continue
218
+ detail_href = row[-1].hrefs[0] if row and row[-1].hrefs else ""
219
+ m = re.search(r"id=(\d+)", detail_href or "")
220
+ detail_id = m.group(1) if m else ""
221
+ if kind == "death":
222
+ rec = {
223
+ "name": cells[0],
224
+ "age": cells[1] if len(cells) > 1 else "",
225
+ "sex": cells[2] if len(cells) > 2 else "",
226
+ "color": cells[3] if len(cells) > 3 else "",
227
+ "date_of_death": cells[4] if len(cells) > 4 else "",
228
+ "county": cells[5] if len(cells) > 5 else "",
229
+ }
230
+ else:
231
+ rec = {
232
+ "name": cells[0],
233
+ "place": cells[1] if len(cells) > 1 else "",
234
+ "county": cells[2] if len(cells) > 2 else "",
235
+ "date_of_birth": cells[3] if len(cells) > 3 else "",
236
+ "father": cells[4] if len(cells) > 4 else "",
237
+ "mother": cells[5] if len(cells) > 5 else "",
238
+ "attendant": cells[6] if len(cells) > 6 else "",
239
+ }
240
+ rec["detail_id"] = detail_id
241
+ rec["detail_url"] = urljoin(PRE1910_PAGE, detail_href) if detail_href else ""
242
+ out.append(rec)
243
+ return out
244
+
245
+
246
+ def _fetch_pages(client, first_html, results_url, parse, limit):
247
+ """Follow the session pager (50/page) until limit or total reached."""
248
+ total = _total_results(first_html)
249
+ records = parse(first_html)
250
+ if total is None:
251
+ total = len(records)
252
+ page = 2
253
+ while len(records) < min(limit, total):
254
+ resp = client.get(
255
+ results_url, params={"PageNumber": page, "recordsPerPage": 50}
256
+ )
257
+ resp.raise_for_status()
258
+ records.extend(parse(resp.text))
259
+ page += 1
260
+ return total, records[:limit]
261
+
262
+
263
+ def _detail_fields(html):
264
+ """Pair each header row on a pre-1910 detail page with its value row."""
265
+ fields = {}
266
+ notes = []
267
+ for table in _parse_tables(html):
268
+ rows = [[_clean(c.text) for c in r] for r in table]
269
+ i = 0
270
+ while i < len(rows):
271
+ row = rows[i]
272
+ if len(row) == 1:
273
+ if row[0] and row[0] != "NOTE":
274
+ notes.append(row[0])
275
+ i += 1
276
+ continue
277
+ if i + 1 < len(rows) and len(rows[i + 1]) == len(row):
278
+ for key, val in zip(row, rows[i + 1]):
279
+ if key:
280
+ fields[key] = val
281
+ i += 2
282
+ else:
283
+ i += 1
284
+ if notes:
285
+ fields["notes"] = "; ".join(notes)
286
+ return fields
287
+
288
+
289
+ def _download_pdf(client, url, dest, overwrite):
290
+ if dest.exists() and not overwrite:
291
+ return dest, True
292
+ with client.stream("GET", url) as resp:
293
+ resp.raise_for_status()
294
+ with dest.open("wb") as fh:
295
+ for chunk in resp.iter_bytes():
296
+ fh.write(chunk)
297
+ return dest, False
298
+
299
+
300
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
301
+ def cli():
302
+ """Search Missouri State Archives vital records (no key, no login)."""
303
+
304
+
305
+ @cli.command("death")
306
+ @click.option("--last", required=True, help="Last name (surname).")
307
+ @click.option("--first", default="", help="First name.")
308
+ @click.option("--middle", default="", help="Middle name.")
309
+ @click.option(
310
+ "--role",
311
+ type=click.Choice(["deceased", "spouse", "father", "mother"]),
312
+ default="deceased",
313
+ show_default=True,
314
+ help="Whose name to search. Spouse/father/mother only for 1953-1975.",
315
+ )
316
+ @click.option(
317
+ "--match",
318
+ type=click.Choice(["contains", "starts-with", "ends-with"]),
319
+ default="contains",
320
+ show_default=True,
321
+ help="Name match type, applied to every name field given.",
322
+ )
323
+ @click.option("--county", default="", help="County as spelled on the site; default all counties.")
324
+ @click.option("--begin-year", type=int, default=1910, show_default=True)
325
+ @click.option("--end-year", type=int, default=1975, show_default=True)
326
+ @click.option("--begin-month", type=int, default=0, show_default=True, help="1-12, 0 = all months.")
327
+ @click.option("--end-month", type=int, default=0, show_default=True, help="1-12, 0 = all months.")
328
+ @click.option("--limit", type=int, default=50, show_default=True, help="Max records (50 per page).")
329
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
330
+ @click.option(
331
+ "--download",
332
+ "download_dir",
333
+ type=click.Path(path_type=Path),
334
+ default=None,
335
+ help="Download each result's certificate PDF into DIR.",
336
+ )
337
+ def cmd_death(
338
+ last, first, middle, role, match, county,
339
+ begin_year, end_year, begin_month, end_month,
340
+ limit, as_json, download_dir,
341
+ ):
342
+ """Search Missouri Death Certificates, 1910-1975 (with images)."""
343
+ if not 1910 <= begin_year <= end_year <= 1975:
344
+ raise click.BadParameter("year range must sit inside 1910-1975.")
345
+ for m in (begin_month, end_month):
346
+ if not 0 <= m <= 12:
347
+ raise click.BadParameter("months must be 0-12 (0 = all).")
348
+ if limit < 1:
349
+ raise click.BadParameter("--limit must be at least 1.")
350
+ method = MATCH_METHODS[match]
351
+ data = {
352
+ "DeathCertNameSearchType": role.capitalize(),
353
+ "LastName": last,
354
+ "LNSearchMethod": method,
355
+ "FirstName": first,
356
+ "FNSearchMethod": method,
357
+ "MiddleName": middle,
358
+ "MNSearchMethod": method,
359
+ "BeginMonth": str(begin_month),
360
+ "BeginYear": str(begin_year),
361
+ "EndMonth": str(end_month),
362
+ "EndYear": str(end_year),
363
+ "CountyName": county or ALL_COUNTIES,
364
+ "Search": "Search",
365
+ }
366
+ with _client() as client:
367
+ first_html = _post_search(client, DEATH_PAGE, DEATH_POST, data)
368
+ total, records = _fetch_pages(
369
+ client, first_html, DEATH_RESULTS, _death_rows, limit
370
+ )
371
+ if download_dir:
372
+ download_dir.mkdir(parents=True, exist_ok=True)
373
+ for rec in records:
374
+ if not rec.get("image"):
375
+ continue
376
+ fname = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(rec["image"]).name)
377
+ dest, skipped = _download_pdf(
378
+ client, rec["image"], download_dir / fname, overwrite=False
379
+ )
380
+ click.echo(
381
+ f"{'Exists (skip)' if skipped else 'Downloaded'}: {dest} "
382
+ f"({dest.stat().st_size:,} bytes)"
383
+ )
384
+ if as_json:
385
+ click.echo(json.dumps({"total": total, "results": records}, indent=2))
386
+ return
387
+ click.echo(f"Total: {total} | showing {len(records)}")
388
+ for rec in records:
389
+ parts = [rec["name"]]
390
+ if rec.get("age"):
391
+ parts.append(f"age {rec['age']}")
392
+ parts.append(rec["date_of_death"])
393
+ parts.append(rec["county"])
394
+ parts.append(f"cert {rec['cert']}")
395
+ if rec.get("image"):
396
+ parts.append(rec["image"])
397
+ click.echo(" | ".join(p for p in parts if p))
398
+
399
+
400
+ @cli.command("pre1910")
401
+ @click.option(
402
+ "--type", "kind",
403
+ type=click.Choice(["birth", "death"]),
404
+ default="death",
405
+ show_default=True,
406
+ help="Record type in the pre-1910 database.",
407
+ )
408
+ @click.option("--name", required=True, help="All or part of a name; the site recommends last name only.")
409
+ @click.option("--county", default="", help="County as spelled on the site; default all counties.")
410
+ @click.option("--limit", type=int, default=50, show_default=True, help="Max records (50 per page).")
411
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
412
+ def cmd_pre1910(kind, name, county, limit, as_json):
413
+ """Search the pre-1910 Birth and Death Records Database (abstracts)."""
414
+ if limit < 1:
415
+ raise click.BadParameter("--limit must be at least 1.")
416
+ if kind == "death":
417
+ data = {
418
+ "DeathCounty": county or ALL_COUNTIES_PRE1910,
419
+ "DeathNameSearch": name,
420
+ "DeathSubmit": "Search",
421
+ }
422
+ else:
423
+ data = {
424
+ "BirthCounty": county or ALL_COUNTIES_PRE1910,
425
+ "BirthNameSearch": name,
426
+ "BirthSubmit": "Search",
427
+ }
428
+ parse = lambda html: _pre1910_rows(html, kind)
429
+ with _client() as client:
430
+ first_html = _post_search(client, PRE1910_PAGE, PRE1910_POST, data)
431
+ total, records = _fetch_pages(
432
+ client, first_html, PRE1910_RESULTS, parse, limit
433
+ )
434
+ if as_json:
435
+ click.echo(json.dumps({"total": total, "results": records}, indent=2))
436
+ return
437
+ click.echo(f"Total: {total} | showing {len(records)}")
438
+ for rec in records:
439
+ if kind == "death":
440
+ parts = [
441
+ rec["name"],
442
+ f"age {rec['age']}" if rec.get("age") else "",
443
+ rec.get("sex", ""),
444
+ rec.get("color", ""),
445
+ rec["date_of_death"],
446
+ rec["county"],
447
+ f"detail {rec['detail_id']}" if rec.get("detail_id") else "",
448
+ ]
449
+ else:
450
+ parts = [
451
+ rec["name"],
452
+ rec.get("place", ""),
453
+ rec["county"],
454
+ rec["date_of_birth"],
455
+ f"father {rec['father']}" if rec.get("father") else "",
456
+ f"mother {rec['mother']}" if rec.get("mother") else "",
457
+ f"detail {rec['detail_id']}" if rec.get("detail_id") else "",
458
+ ]
459
+ click.echo(" | ".join(p for p in parts if p))
460
+
461
+
462
+ @cli.command("detail")
463
+ @click.argument("ids", nargs=-1, required=True)
464
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
465
+ def cmd_detail(ids, as_json):
466
+ """Fetch full abstracts for pre-1910 record IDs (from `pre1910`)."""
467
+ records = []
468
+ with _client() as client:
469
+ for rid in ids:
470
+ clean = re.sub(r"\D+", "", rid)
471
+ url = f"{PRE1910_DETAIL}?id={clean}"
472
+ resp = client.get(url)
473
+ resp.raise_for_status()
474
+ records.append({"id": clean, "url": url, "fields": _detail_fields(resp.text)})
475
+ if as_json:
476
+ click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
477
+ return
478
+ for idx, rec in enumerate(records):
479
+ if idx > 0:
480
+ click.echo("")
481
+ click.echo(f"Detail {rec['id']}: {rec['url']}")
482
+ for key, val in rec["fields"].items():
483
+ click.echo(f" {key}: {val}")
484
+
485
+
486
+ @cli.command("download")
487
+ @click.argument("urls", nargs=-1, required=True)
488
+ @click.option(
489
+ "--out", "out_dir",
490
+ type=click.Path(path_type=Path),
491
+ default=Path("mo-death-certs"),
492
+ show_default=True,
493
+ help="Output directory.",
494
+ )
495
+ @click.option("--overwrite", is_flag=True, help="Re-download files that already exist.")
496
+ def cmd_download(urls, out_dir, overwrite):
497
+ """Download death-certificate PDFs by image URL (from `death`)."""
498
+ out_dir.mkdir(parents=True, exist_ok=True)
499
+ with _client() as client:
500
+ for url in urls:
501
+ fname = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(url).name) or "certificate.pdf"
502
+ dest, skipped = _download_pdf(client, url, out_dir / fname, overwrite)
503
+ click.echo(
504
+ f"{'Exists (skip)' if skipped else 'Downloaded'}: {dest} "
505
+ f"({dest.stat().st_size:,} bytes)"
506
+ )
507
+
508
+
509
+ @cli.command("mdh")
510
+ def cmd_mdh():
511
+ """Show the Missouri Digital Heritage browser path (no machine interface)."""
512
+ click.echo("Missouri Digital Heritage has no verified machine interface.")
513
+ click.echo(f" Home: {MDH_HOME}")
514
+ click.echo(f" Advanced Search (browser): {MDH_SEARCH}")
515
+ click.echo(f" Missouri State Archives: {ARCHIVES_HOME}")
516
+ click.echo(" CONTENTdm dmwebservices returns 403 (Cloudflare) to automated requests,")
517
+ click.echo(" and no GET search URL for the Advanced Search was verified.")
518
+ click.echo(" Use the browser for MDH collections (soldiers, land patents,")
519
+ click.echo(" naturalization, newspapers, plat books). The two vital-records")
520
+ click.echo(" databases are covered by this CLI: `death` and `pre1910`.")
521
+
522
+
523
+ if __name__ == "__main__":
524
+ try:
525
+ cli()
526
+ except httpx.HTTPStatusError as exc:
527
+ click.echo(f"HTTP error {exc.response.status_code}: {exc.request.url}", err=True)
528
+ sys.exit(1)
@@ -0,0 +1,118 @@
1
+ ---
2
+ name: nara-catalog-search
3
+ description: Search, inspect, and download records from the National Archives Catalog via the bundled uv-based `nara` CLI, website advanced search, or v2 API. Covers CLI usage, query-string syntax, q operators, fielded parameters, filters, date and Congress ranges, pagination, and worked examples. Use when querying NARA, inspecting NAIDs, downloading digitized archival scans, or verifying genealogy records.
4
+ ---
5
+
6
+ # NARA Catalog Search
7
+
8
+ This skill includes a standalone executable Python CLI at `skills/nara-catalog-search/scripts/nara` using a PEP 723 `#!/usr/bin/env -S uv run --script` shebang with inline dependencies (`click`, `httpx`, `playwright`). No virtualenv setup or API key is required.
9
+
10
+ - **Without `NARA_API_KEY` (default):** runs headless Chromium (auto-detecting system `chromium` or `google-chrome`) against `catalog.archives.gov` and reads the structured Catalog JSON responses.
11
+ - **With `NARA_API_KEY`:** queries the official v2 API (`https://catalog.archives.gov/api/v2/records/search`) over HTTP directly. Pass `--browser` to force website mode.
12
+ - **Compact output by default:** JSON and text outputs keep only non-empty archival citation fields (`naId`, `title`, `url`, `level`, `rg`, `series`, `dates`, `microform`, `access`, `use`, `location`, `scope`, `objectCount`). Full digital object URL lists are excluded unless `--objects` is passed (and can be sliced with `--pages`).
13
+
14
+ ## Bundled CLI (`scripts/nara`)
15
+
16
+ Path: `skills/nara-catalog-search/scripts/nara`
17
+
18
+ ### Search records (single or batched in one browser session)
19
+
20
+ ```bash
21
+ # Single exact-phrase search in Record Group 15 (Department of Veterans Affairs pension files)
22
+ skills/nara-catalog-search/scripts/nara search '"Harriet Tubman"' --rg 15
23
+
24
+ # Batch multiple queries sharing one headless Chromium session (fast)
25
+ skills/nara-catalog-search/scripts/nara search '"Clara Barton"' '"Frederick Douglass"' 'Gettysburg AND Lincoln' --online --json
26
+
27
+ # Digital records only, filtered by level, date range, and material type
28
+ skills/nara-catalog-search/scripts/nara search '"Abraham Lincoln"' --level fileUnit,item --online --start-date 1860 --end-date 1865 --type "Textual Records"
29
+ ```
30
+
31
+ ### Inspect one or more NAIDs
32
+
33
+ ```bash
34
+ # Compact metadata and file counts for multiple NAIDs (reuses one browser)
35
+ skills/nara-catalog-search/scripts/nara get <naid-1> <naid-2> --json
36
+
37
+ # Include sliced digital object URLs for large rolls
38
+ skills/nara-catalog-search/scripts/nara get <naid> --objects --pages 1-10 --json
39
+
40
+ # Print extracted OCR or community transcriptions if available
41
+ skills/nara-catalog-search/scripts/nara get <naid> --text
42
+ ```
43
+
44
+ Note on large multi-page file units: `nara get --text` prints text only when NARA's record object stores `extractedText`, `otherExtractedText`, or community transcriptions, and NARA's catalog search proxy response does not include page-level match highlights. When a search matches inside a large digitized file unit (for example hundreds of pages) with no `extractedText` returned by `get --text`, open `https://catalog.archives.gov/id/<naId>` in a browser to locate the matching page.
45
+
46
+ ### Download digitized scans with compact provenance metadata
47
+
48
+ ```bash
49
+ # Download selected 1-based pages plus compact metadata.json
50
+ skills/nara-catalog-search/scripts/nara download <naid> --pages 1-5 --out ./downloads/nara-<naid>
51
+
52
+ # Download all images in a file unit
53
+ skills/nara-catalog-search/scripts/nara download <naid> --out ./downloads/nara-<naid>
54
+ ```
55
+
56
+ ### Build verified search URLs offline
57
+
58
+ ```bash
59
+ skills/nara-catalog-search/scripts/nara url '"Harriet Tubman"' --rg 15 --online
60
+ skills/nara-catalog-search/scripts/nara url '"Clara Barton"' --level item --api
61
+ ```
62
+
63
+ ### Environment variables
64
+
65
+ - `NARA_API_KEY`: optional NARA Catalog v2 API key for direct HTTP queries.
66
+ - `NARA_BROWSER`: optional path to a Chromium or Chrome binary (defaults to `chromium`, `chromium-browser`, `google-chrome`, or Playwright's bundled browser).
67
+
68
+ ## Website search & query string rules (verified live 2026-11-23)
69
+
70
+ - Basic: `https://catalog.archives.gov/search?q=<query>&page=<n>`
71
+ - Advanced builder: `https://catalog.archives.gov/advanced-search` (submits to `/search`)
72
+ - Record page: `https://catalog.archives.gov/id/<naId>`
73
+ - Help: `https://www.archives.gov/research/catalog/help/using`
74
+ - No sign-in or API key is needed for the website.
75
+
76
+ Rules:
77
+ - The search goes to `/search`, with `q=` first.
78
+ - Filters are separate parameters joined by `&`.
79
+ - Defaults add nothing: "All Archival Descriptions" and "All fields" produce no parameter.
80
+ - Multiple values in one filter are comma-separated inside a single parameter, never repeated keys. Example: `levelOfDescription=item%2CfileUnit`.
81
+ - URL encoding: space `%20`, double quote `%22`, comma `%2C`.
82
+ - Level values are lowercase camelCase: `recordGroup`, `collection`, `series`, `fileUnit`, `item`.
83
+
84
+ ### Example URL patterns
85
+
86
+ - Exact phrase, item level: `https://catalog.archives.gov/search?q=%22Clara%20Barton%22&levelOfDescription=item`
87
+ - Keyword, digital content only: `https://catalog.archives.gov/search?q=Harriet%20Tubman&availableOnline=true&dataSource=description`
88
+ - Two levels: `https://catalog.archives.gov/search?q=Frederick%20Douglass&levelOfDescription=item%2CfileUnit`
89
+
90
+ ## `q` syntax
91
+
92
+ - Boolean operators `AND`, `OR`, `NOT`; wildcard `*`; exact phrase with double quotes: `"Clara Barton"`.
93
+ - Plain keywords match broadly (`Clara Barton` unquoted matches either word anywhere). Quote exact names to narrow results.
94
+ - Wildcards: `photo*`, `WJC*`, `4*`.
95
+ - Comma-separated lists in control-number fields: `21-A-1, 5635483`; record group: `255, 404`; collection: `WJC-FCIP, WJC-WHOO`.
96
+
97
+ ## Field-selector mapping to API parameters
98
+
99
+ - All fields -> `q` (verified)
100
+ - Title -> `title` (exact: `title_is`)
101
+ - Creator -> `creators`
102
+ - Person or Organization -> `personOrOrg`
103
+ - Geographic Reference -> `geographicReference`
104
+ - Tags -> `tagContribution`; Transcriptions -> `transcriptionContribution`; Comments -> `commentContribution`
105
+ - Local Identifier -> `localIdentifier` (`localIdentifier_is`); National Archives Identifier -> `naId` (`naId_is`); Record Group Number -> `recordGroupNumber`; Collection Identifier -> `collectionIdentifier`
106
+ - Location -> `referenceUnits`
107
+ - Type of Material -> `typeOfMaterials` (`Textual Records`, `Photographs and other Graphic Materials`, `Moving Images`, `Maps and Charts`, `Architectural and Engineering Drawings`, `Data Files`, `Sound Recordings`, `Artifacts`)
108
+ - Beginning/Ending Date -> `startDate` / `endDate` (`YYYY`, `YYYY-MM`, or `YYYY-MM-DD`); exact date -> `exactDate`
109
+ - Beginning/Ending Congress -> `beginCongress` / `endCongress` / `congressNumber`
110
+
111
+ ## API v2 reference (optional key)
112
+
113
+ - Base: `GET https://catalog.archives.gov/api/v2/records/search`
114
+ - Auth: `x-api-key` header (request a free read-only key by emailing `Catalog_API@nara.gov`; limit 10,000 queries/month; never commit keys).
115
+ - Docs: `https://catalog.archives.gov/api/v2/api-docs/` (`swagger.json` at `https://catalog.archives.gov/api/v2/swagger.json`).
116
+ - Other endpoints: `/records/parentNaId/{parentNaId}`, `/extractedText/{naId}`, `/records/stats`, `/records/search/by-tag`, `/by-transcription`, `/by-comment`.
117
+ - Attribution: services using the API must display "This product uses the National Archives Catalog API but is not endorsed or certified by the National Archives and Records Administration."
118
+ - Terms note: do not scrape or bulk-mirror the whole Catalog; use the AWS Registry of Open Data dataset for bulk transfers.