@kinloom/cli 0.1.1 → 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 (101) 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/ops/audit.d.ts +138 -0
  50. package/dist/commands/ops/audit.d.ts.map +1 -0
  51. package/dist/commands/ops/audit.js +867 -0
  52. package/dist/commands/ops/audit.js.map +1 -0
  53. package/dist/commands/ops/context.d.ts +100 -0
  54. package/dist/commands/ops/context.d.ts.map +1 -0
  55. package/dist/commands/ops/context.js +917 -0
  56. package/dist/commands/ops/context.js.map +1 -0
  57. package/dist/commands/ops/help.d.ts +6 -0
  58. package/dist/commands/ops/help.d.ts.map +1 -0
  59. package/dist/commands/ops/help.js +74 -0
  60. package/dist/commands/ops/help.js.map +1 -0
  61. package/dist/commands/ops/index.d.ts +6 -0
  62. package/dist/commands/ops/index.d.ts.map +1 -0
  63. package/dist/commands/ops/index.js +6 -0
  64. package/dist/commands/ops/index.js.map +1 -0
  65. package/dist/commands/ops/integrate.d.ts +56 -0
  66. package/dist/commands/ops/integrate.d.ts.map +1 -0
  67. package/dist/commands/ops/integrate.js +872 -0
  68. package/dist/commands/ops/integrate.js.map +1 -0
  69. package/dist/commands/ops/sync.d.ts +177 -0
  70. package/dist/commands/ops/sync.d.ts.map +1 -0
  71. package/dist/commands/ops/sync.js +1078 -0
  72. package/dist/commands/ops/sync.js.map +1 -0
  73. package/dist/commands/ops/telemetry.d.ts +79 -0
  74. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  75. package/dist/commands/ops/telemetry.js +249 -0
  76. package/dist/commands/ops/telemetry.js.map +1 -0
  77. package/dist/commands/records/help.d.ts +18 -0
  78. package/dist/commands/records/help.d.ts.map +1 -0
  79. package/dist/commands/records/help.js +174 -0
  80. package/dist/commands/records/help.js.map +1 -0
  81. package/dist/commands/records/index.d.ts +5 -0
  82. package/dist/commands/records/index.d.ts.map +1 -0
  83. package/dist/commands/records/index.js +5 -0
  84. package/dist/commands/records/index.js.map +1 -0
  85. package/dist/commands/records/registry.d.ts +32 -0
  86. package/dist/commands/records/registry.d.ts.map +1 -0
  87. package/dist/commands/records/registry.js +227 -0
  88. package/dist/commands/records/registry.js.map +1 -0
  89. package/dist/commands/records/resolve.d.ts +14 -0
  90. package/dist/commands/records/resolve.d.ts.map +1 -0
  91. package/dist/commands/records/resolve.js +61 -0
  92. package/dist/commands/records/resolve.js.map +1 -0
  93. package/dist/commands/records/runner.d.ts +25 -0
  94. package/dist/commands/records/runner.d.ts.map +1 -0
  95. package/dist/commands/records/runner.js +224 -0
  96. package/dist/commands/records/runner.js.map +1 -0
  97. package/dist/index.d.ts +2 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +2 -0
  100. package/dist/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -0,0 +1,466 @@
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
+ """CLI for Library of Virginia research: Chancery Records Index, Primo catalog.
10
+
11
+ All routes below were verified live 2026-11-24 with plain
12
+ HTTP (no key, no account, no browser):
13
+
14
+ - Chancery search is a POST form to old.lva.virginia.gov/chancery/default.asp
15
+ accepting surname, match mode, and locality filters.
16
+ - Case detail is a GET: /chancery/case_detail.asp?CFN=<loc>-<year>-<number>.
17
+ - Case images are listed by /chancery/case_images.asp?CFN=<CFN> as
18
+ myImages[N]="/ChanceryImg/<locality>/Box<nnn>/<cfn>_<####>.pdf";
19
+ each page PDF and the whole-case ZIP
20
+ (/chancery/zip/download.php?cfn=<CFN>) return 200.
21
+ - The Primo catalog has a public, key-free JSON API (PNXS):
22
+ lva.primo.exlibrisgroup.com/primaws/rest/pub/pnxs?q=any,contains,<q>
23
+ &vid=01LVA_INST:01LVA&scope=MyInstitution.
24
+
25
+ Virginia Chronicle (virginiachronicle.com) is behind Cloudflare: curl and
26
+ headless Chromium both get "Just a moment..." (2026-11-24). No machine
27
+ interface was verified for it; use the `url --chronicle` pointer and search
28
+ in the browser. ARVAS (arvasarchive.org) returns an empty 202 to plain HTTP
29
+ and is likewise browser-only. The old Aleph Land Office index host
30
+ (lva1.hosted.exlibrisgroup.com) was unreachable on 2026-11-24.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import html as _html
36
+ import json
37
+ import re
38
+ import sys
39
+ from pathlib import Path
40
+ from urllib.parse import quote, urlencode
41
+
42
+ import click
43
+ import httpx
44
+
45
+ CHANCERY_BASE = "https://old.lva.virginia.gov/chancery"
46
+ CHANCERY_SEARCH = CHANCERY_BASE + "/default.asp"
47
+ CHANCERY_DETAIL = CHANCERY_BASE + "/case_detail.asp"
48
+ CHANCERY_IMAGES = CHANCERY_BASE + "/case_images.asp"
49
+ CHANCERY_ZIP = CHANCERY_BASE + "/zip/download.php"
50
+ CHANCERY_AVAILABLE = CHANCERY_BASE + "/available.asp"
51
+ PRIMO_BASE = "https://lva.primo.exlibrisgroup.com"
52
+ PRIMO_PNXS = PRIMO_BASE + "/primaws/rest/pub/pnxs"
53
+ PRIMO_VID = "01LVA_INST:01LVA"
54
+ USER_AGENT = (
55
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
56
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
57
+ )
58
+ MATCH_OPS = ("Exact", "Starts", "Includes")
59
+ CATALOG_FIELDS = ("any", "title", "creator")
60
+
61
+
62
+ def _client() -> httpx.Client:
63
+ return httpx.Client(headers={"User-Agent": USER_AGENT}, timeout=60.0, follow_redirects=True)
64
+
65
+
66
+ def _clean(text: str) -> str:
67
+ text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
68
+ text = re.sub(r"<[^>]+>", " ", text)
69
+ text = _html.unescape(re.sub(r"[ \t]+", " ", text))
70
+ return text.strip()
71
+
72
+
73
+ def _names(cell: str) -> list[str]:
74
+ return [line.strip() for line in _clean(cell).splitlines() if line.strip()]
75
+
76
+
77
+ def parse_search_page(page: str) -> dict:
78
+ """Parse a Chancery default.asp results page into records + paging info."""
79
+ total_m = re.search(r"Your search returned (\d+) record\(s\). You are now viewing records (\d+) through (\d+)", page)
80
+ total = int(total_m.group(1)) if total_m else 0
81
+ first = int(total_m.group(2)) if total_m else 0
82
+ last = int(total_m.group(3)) if total_m else 0
83
+ pat = re.compile(
84
+ r"<strong>Index Number:</strong>\s*([^<]+?)\s*</span>\s*"
85
+ r"<a href=\"case_detail\.asp\?CFN=([0-9\-]+)\"[^>]*>.*?"
86
+ r"<strong>Locality:</strong>\s*([^<]+?)\s*</td>.*?"
87
+ r"<td valign=\"top\">\s*(.*?)\s*</td>\s*<td valign=\"top\">\s*(.*?)\s*</td>",
88
+ re.S | re.I,
89
+ )
90
+ records = []
91
+ for m in pat.finditer(page):
92
+ records.append({
93
+ "index_number": _html.unescape(m.group(1).strip()),
94
+ "cfn": m.group(2),
95
+ "locality": _html.unescape(m.group(3).strip()),
96
+ "plaintiffs": _names(m.group(4)),
97
+ "defendants": _names(m.group(5)),
98
+ "case_url": CHANCERY_DETAIL + "?CFN=" + m.group(2),
99
+ })
100
+ return {"total": total, "first": first, "last": last, "records": records}
101
+
102
+
103
+ def parse_case_page(page: str) -> dict:
104
+ """Parse a Chancery case_detail.asp page."""
105
+ def section(label: str) -> str:
106
+ m = re.search(r"<strong>" + re.escape(label) + r"</strong></td></tr>\s*<tr>\s*<td[^>]*>(.*?)</td>", page, re.S | re.I)
107
+ return _clean(m.group(1)) if m else ""
108
+ head = re.search(
109
+ r"<strong>Locality</strong></td><td[^>]*><strong>Index Number</strong></td><td[^>]*><strong>Original Case Number</strong></td></tr>\s*<tr>\s*<td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>",
110
+ page, re.S | re.I)
111
+ parties = re.search(
112
+ r"<strong>Plaintiff\(s\)</strong></td><td[^>]*><strong>Defendant\(s\)</strong></td></tr>\s*<tr>\s*<td[^>]*>(.*?)</td>\s*<td[^>]*>(.*?)</td>",
113
+ page, re.S | re.I)
114
+ surnames = re.search(r"<strong>Surname\(s\)</strong></td></tr>\s*<tr><td[^>]*>(.*?)</td>", page, re.S | re.I)
115
+ plat = re.search(r"<strong>Plat\?</strong></td></tr>\s*<tr><td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>", page, re.S | re.I)
116
+ fmt = section("Format")
117
+ wills = ""
118
+ wm = re.search(r"<strong>Wills</strong></td><td[^>]*>.*?Plat\?.*?</tr>\s*<tr><td[^>]*>(.*?)</td>", page, re.S | re.I)
119
+ if wm:
120
+ wills = _clean(wm.group(1))
121
+ return {
122
+ "locality": _html.unescape(head.group(1).strip()) if head else "",
123
+ "index_number": _html.unescape(head.group(2).strip()) if head else "",
124
+ "original_case_number": _html.unescape(head.group(3).strip()) if head else "",
125
+ "plaintiffs": _names(parties.group(1)) if parties else [],
126
+ "defendants": _names(parties.group(2)) if parties else [],
127
+ "surnames": _names(surnames.group(1)) if surnames else [],
128
+ "wills": wills,
129
+ "plat": _html.unescape(plat.group(2).strip()) if plat else "",
130
+ "format": fmt,
131
+ }
132
+
133
+
134
+ def parse_images_page(page: str) -> dict:
135
+ """Parse case_images.asp: myImages[N] PDF list + total page count."""
136
+ urls = re.findall(r'myImages\[\d+\]\s*=\s*"([^"]+)"', page)
137
+ urls = [u for u in urls if u]
138
+ total_m = re.search(r"of\s+(\d+)\s+prev", _clean(page))
139
+ total = int(total_m.group(1)) if total_m else len(urls)
140
+ zip_m = re.search(r'href="([^"]*download\.php\?cfn=[^"]*)"', page, re.I)
141
+ return {
142
+ "total_pages": total,
143
+ "page_pdfs": [CHANCERY_BASE.rsplit("/chancery", 1)[0] + u if u.startswith("/") else u for u in urls],
144
+ "zip_url": ("https://old.lva.virginia.gov" + _html.unescape(zip_m.group(1))) if zip_m else CHANCERY_ZIP + "?cfn=",
145
+ }
146
+
147
+
148
+ def parse_localities_page(page: str) -> list[dict]:
149
+ """Parse available.asp locality availability table."""
150
+ rows = []
151
+ for m in re.finditer(
152
+ r"<TR><TD>([^<]*)</td><TD>([^<]*)</td><TD>([^<]*)</td><TD>([^<]*)</td><TD>(.*?)</td></TR>",
153
+ page, re.S | re.I):
154
+ rows.append({
155
+ "locality": _html.unescape(m.group(1).replace("&nbsp;", " ").strip()),
156
+ "region": _html.unescape(m.group(2).replace("&nbsp;", " ").strip()),
157
+ "time_frame": _html.unescape(m.group(3).replace("&nbsp;", " ").strip()),
158
+ "viewing_status": _html.unescape(m.group(4).replace("&nbsp;", " ").strip()),
159
+ "notes": _clean(m.group(5)),
160
+ })
161
+ return rows
162
+
163
+
164
+ def parse_page_spec(spec: str, total: int) -> list[int]:
165
+ """1-based page slice like '1-5,10' or 'all' (NARA CLI convention)."""
166
+ if spec.strip().lower() == "all":
167
+ return list(range(1, total + 1))
168
+ out: list[int] = []
169
+ for part in spec.split(","):
170
+ part = part.strip()
171
+ if "-" in part:
172
+ a, b = part.split("-", 1)
173
+ out.extend(range(int(a), int(b) + 1))
174
+ elif part:
175
+ out.append(int(part))
176
+ return sorted(set(n for n in out if 1 <= n <= total))
177
+
178
+
179
+ def _pnxs_record(doc: dict) -> dict:
180
+ pnx = doc.get("pnx", {})
181
+ disp = pnx.get("display", {})
182
+ control = pnx.get("control", {})
183
+ recordid = (control.get("recordid") or [""])[0]
184
+ def first(key: str) -> str:
185
+ vals = disp.get(key) or []
186
+ return vals[0].strip() if vals else ""
187
+ return {
188
+ "recordid": recordid,
189
+ "title": first("title"),
190
+ "creator": first("creator"),
191
+ "date": first("creationdate"),
192
+ "type": first("type"),
193
+ "source": first("source"),
194
+ "record_url": (
195
+ PRIMO_BASE + "/discovery/fulldisplay?docid=" + recordid
196
+ + "&context=L&vid=" + quote(PRIMO_VID, safe="")
197
+ + "&lang=en&search_scope=MyInstitution"
198
+ ) if recordid else "",
199
+ }
200
+
201
+
202
+ def _fmt_record_text(rec: dict) -> str:
203
+ lines = [f"{rec['cfn']} {rec['locality']} index {rec['index_number']}"]
204
+ if rec["plaintiffs"]:
205
+ lines.append(" P: " + "; ".join(rec["plaintiffs"]))
206
+ if rec["defendants"]:
207
+ lines.append(" D: " + "; ".join(rec["defendants"]))
208
+ lines.append(" " + rec["case_url"])
209
+ return "\n".join(lines)
210
+
211
+
212
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
213
+ def cli() -> None:
214
+ """Search the Library of Virginia: Chancery Records Index and Primo catalog."""
215
+
216
+
217
+ @cli.group("chancery")
218
+ def chancery() -> None:
219
+ """Chancery Records Index (old.lva.virginia.gov/chancery)."""
220
+
221
+
222
+ @chancery.command("search")
223
+ @click.argument("surnames", nargs=-1, required=True)
224
+ @click.option("--locality", default="All", show_default=True,
225
+ help="County/city, e.g. 'ALBEMARLE CO'. Default All. Use `chancery localities` to list values.")
226
+ @click.option("--match", type=click.Choice(["Exact", "Starts", "Includes"], case_sensitive=False), default="Starts", show_default=True,
227
+ help="How the surname match works (form values Exact/Starts/Includes).")
228
+ @click.option("--surname2", default=None, help="Second surname (ANDed by the index form).")
229
+ @click.option("--plaintiff-last", default=None, help="Plaintiff last name.")
230
+ @click.option("--plaintiff-first", default=None, help="Plaintiff first name.")
231
+ @click.option("--defendant-last", default=None, help="Defendant last name.")
232
+ @click.option("--defendant-first", default=None, help="Defendant first name.")
233
+ @click.option("--year-from", default=None, help="First year of case (strDate1).")
234
+ @click.option("--year-to", default=None, help="Last year of case (strDate2).")
235
+ @click.option("--index-number", default=None, help="Index number, e.g. YYYY-NNN (txtIndexNum).")
236
+ @click.option("--local-case-number", default=None, help="Local case file number (txtLclCFN).")
237
+ @click.option("--enslaved", is_flag=True, help="Only cases referencing enslaved persons.")
238
+ @click.option("--free", is_flag=True, help="Only cases referencing free persons.")
239
+ @click.option("--plats", is_flag=True, help="Only cases with plats available.")
240
+ @click.option("--pages", default="1", show_default=True, help="Result pages to fetch: '1', '1-3', '1,3', or 'all' (20 records per page).")
241
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
242
+ def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, plaintiff_first,
243
+ defendant_last, defendant_first, year_from, year_to, index_number,
244
+ local_case_number, enslaved, free, plats, pages, as_json):
245
+ """Search the Chancery Records Index by surname (more surnames = OR)."""
246
+ match = match.capitalize()
247
+ all_records: list[dict] = []
248
+ total = 0
249
+ with _client() as c:
250
+ for surname in surnames:
251
+ form: dict[str, str] = {
252
+ "surname1": surname, "sn1select": match,
253
+ "plnlstName": plaintiff_last or "", "plselect": match,
254
+ "plnfrstName": plaintiff_first or "", "pfselect": match,
255
+ "deflstName": defendant_last or "", "dlselect": match,
256
+ "deffrstName": defendant_first or "", "dfselect": match,
257
+ "strDate1": year_from or "", "strDate2": year_to or "",
258
+ "txtIndexNum": index_number or "", "txtLclCFN": local_case_number or "",
259
+ "Submit": "Search",
260
+ }
261
+ if surname2:
262
+ form["surname2"] = surname2
263
+ form["sn2select"] = match
264
+ if enslaved:
265
+ form["chkEnslaved"] = "on"
266
+ if free:
267
+ form["chkFree"] = "on"
268
+ if plats:
269
+ form["chkPlat"] = "on"
270
+ first_page = 1
271
+ form["LOC"] = locality
272
+ resp = c.post(CHANCERY_SEARCH, data=form)
273
+ resp.raise_for_status()
274
+ parsed = parse_search_page(resp.text)
275
+ total += parsed["total"]
276
+ if pages.strip().lower() == "all":
277
+ wanted = list(range(1, (total + 19) // 20 + 1)) or [1]
278
+ else:
279
+ wanted = parse_page_spec(pages, max((total + 19) // 20, 1))
280
+ for pn in wanted:
281
+ if pn == first_page:
282
+ all_records.extend(parsed["records"])
283
+ continue
284
+ form2 = dict(form)
285
+ form2["intPage"] = str(pn)
286
+ r2 = c.post(CHANCERY_SEARCH, data=form2)
287
+ r2.raise_for_status()
288
+ all_records.extend(parse_search_page(r2.text)["records"])
289
+ if as_json:
290
+ click.echo(json.dumps({"total": total, "returned": len(all_records), "records": all_records}, indent=1))
291
+ return
292
+ click.echo(f"{total} record(s); showing {len(all_records)}:")
293
+ for rec in all_records:
294
+ click.echo(_fmt_record_text(rec))
295
+ click.echo()
296
+
297
+
298
+ @chancery.command("case")
299
+ @click.argument("cfn")
300
+ @click.option("--images", is_flag=True, help="Also list the scanned page PDFs and ZIP URL.")
301
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
302
+ def cmd_chancery_case(cfn: str, images: bool, as_json: bool) -> None:
303
+ """Show one chancery cause by CFN (locality-year-number)."""
304
+ with _client() as c:
305
+ resp = c.get(CHANCERY_DETAIL, params={"CFN": cfn})
306
+ resp.raise_for_status()
307
+ detail = parse_case_page(resp.text)
308
+ detail["cfn"] = cfn
309
+ detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
310
+ if images:
311
+ with _client() as c:
312
+ resp = c.get(CHANCERY_IMAGES, params={"CFN": cfn})
313
+ resp.raise_for_status()
314
+ detail["images"] = parse_images_page(resp.text)
315
+ if as_json:
316
+ click.echo(json.dumps(detail, indent=1))
317
+ return
318
+ click.echo(f"{cfn} {detail['locality']} index {detail['index_number']} (original case no. {detail['original_case_number'] or 'n/a'})")
319
+ click.echo("Plaintiff(s): " + ("; ".join(detail["plaintiffs"]) or "n/a"))
320
+ click.echo("Defendant(s): " + ("; ".join(detail["defendants"]) or "n/a"))
321
+ click.echo("Surname(s): " + (", ".join(detail["surnames"]) or "n/a"))
322
+ click.echo(f"Wills: {detail['wills'] or 'n/a'} Plat: {detail['plat'] or 'n/a'} Format: {detail['format'] or 'n/a'}")
323
+ click.echo(detail["case_url"])
324
+ if images:
325
+ imgs = detail["images"]
326
+ click.echo(f"Images: {imgs['total_pages']} page(s)")
327
+ for u in imgs["page_pdfs"]:
328
+ click.echo(" " + u)
329
+ click.echo("ZIP: " + imgs["zip_url"])
330
+
331
+
332
+ @chancery.command("download")
333
+ @click.argument("cfn")
334
+ @click.option("--out", "out_dir", default=None, type=click.Path(path_type=Path),
335
+ help="Output directory (default: ./va-chancery-<cfn>).")
336
+ @click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5' or 'all'.")
337
+ @click.option("--zip", "as_zip", is_flag=True, help="Download the whole-case ZIP instead of page PDFs.")
338
+ @click.option("--overwrite", is_flag=True, help="Overwrite existing files.")
339
+ def cmd_chancery_download(cfn: str, out_dir: Path | None, pages: str, as_zip: bool, overwrite: bool) -> None:
340
+ """Download the scanned pages (or whole-case ZIP) for one chancery cause."""
341
+ out_dir = out_dir or Path(f"va-chancery-{cfn}")
342
+ out_dir.mkdir(parents=True, exist_ok=True)
343
+ with _client() as c:
344
+ resp = c.get(CHANCERY_DETAIL, params={"CFN": cfn})
345
+ resp.raise_for_status()
346
+ detail = parse_case_page(resp.text)
347
+ detail["cfn"] = cfn
348
+ detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
349
+ imgs = None
350
+ if not as_zip:
351
+ r2 = c.get(CHANCERY_IMAGES, params={"CFN": cfn})
352
+ r2.raise_for_status()
353
+ imgs = parse_images_page(r2.text)
354
+ detail["images"] = imgs
355
+ (out_dir / "metadata.json").write_text(json.dumps(detail, indent=1), encoding="utf-8")
356
+ if as_zip:
357
+ zip_url = (imgs["zip_url"] if imgs else None) or (CHANCERY_ZIP + "?cfn=" + cfn)
358
+ dest = out_dir / f"{cfn}.zip"
359
+ if dest.exists() and not overwrite:
360
+ click.echo(f"exists, skipping: {dest}")
361
+ return
362
+ with c.stream("GET", zip_url) as r:
363
+ r.raise_for_status()
364
+ with open(dest, "wb") as f:
365
+ for chunk in r.iter_bytes():
366
+ f.write(chunk)
367
+ click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
368
+ return
369
+ assert imgs is not None
370
+ wanted = parse_page_spec(pages, imgs["total_pages"])
371
+ for n in wanted:
372
+ url = imgs["page_pdfs"][n - 1]
373
+ dest = out_dir / Path(url).name
374
+ if dest.exists() and not overwrite:
375
+ click.echo(f"exists, skipping: {dest.name}")
376
+ continue
377
+ with c.stream("GET", url) as r:
378
+ r.raise_for_status()
379
+ with open(dest, "wb") as f:
380
+ for chunk in r.iter_bytes():
381
+ f.write(chunk)
382
+ click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
383
+ click.echo(f"metadata: {out_dir / 'metadata.json'}")
384
+
385
+
386
+ @chancery.command("localities")
387
+ @click.option("--status", default=None, help="Filter by viewing status substring, e.g. Scanned.")
388
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
389
+ def cmd_chancery_localities(status: str | None, as_json: bool) -> None:
390
+ """List per-locality chancery coverage from available.asp."""
391
+ with _client() as c:
392
+ resp = c.get(CHANCERY_AVAILABLE)
393
+ resp.raise_for_status()
394
+ rows = parse_localities_page(resp.text)
395
+ if status:
396
+ rows = [r for r in rows if status.lower() in r["viewing_status"].lower()]
397
+ if as_json:
398
+ click.echo(json.dumps(rows, indent=1))
399
+ return
400
+ for r in rows:
401
+ click.echo(f"{r['locality']:20s} {r['region']:22s} {r['time_frame']:14s} {r['viewing_status']}")
402
+ click.echo(f"{len(rows)} localities")
403
+
404
+
405
+ @cli.command("catalog")
406
+ @click.argument("query")
407
+ @click.option("--field", type=click.Choice(list(CATALOG_FIELDS)), default="any", show_default=True,
408
+ help="PNXS search field (verified: any, title, creator).")
409
+ @click.option("--limit", default=10, show_default=True, type=int, help="Results per page (PNXS limit).")
410
+ @click.option("--offset", default=0, show_default=True, type=int, help="Result offset (PNXS offset).")
411
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
412
+ def cmd_catalog(query: str, field: str, limit: int, offset: int, as_json: bool) -> None:
413
+ """Search the Library of Virginia catalog via the public Primo PNXS API."""
414
+ params = {
415
+ "q": f"{field},contains,{query}",
416
+ "vid": PRIMO_VID, "scope": "MyInstitution", "lang": "en",
417
+ "limit": str(limit), "offset": str(offset),
418
+ }
419
+ with _client() as c:
420
+ resp = c.get(PRIMO_PNXS, params=params)
421
+ resp.raise_for_status()
422
+ data = resp.json()
423
+ info = data.get("info", {})
424
+ records = [_pnxs_record(d) for d in data.get("docs", [])]
425
+ if as_json:
426
+ click.echo(json.dumps({"total": info.get("total"), "first": info.get("first"),
427
+ "last": info.get("last"), "records": records}, indent=1))
428
+ return
429
+ click.echo(f"{info.get('total')} result(s); showing {info.get('first')}-{info.get('last')}:")
430
+ for rec in records:
431
+ click.echo(f"{rec['title'] or '(no title)'}")
432
+ click.echo(f" {rec['creator'] or ''} {rec['date'] or ''} [{rec['type'] or ''}]".rstrip())
433
+ click.echo(f" {rec['record_url']}")
434
+
435
+
436
+ @cli.command("url")
437
+ @click.option("--chancery-case", "chancery_case", default=None, help="CFN (locality-year-number).")
438
+ @click.option("--catalog", "catalog_query", default=None, help="Catalog search term (Primo search URL).")
439
+ @click.option("--chronicle", is_flag=True, help="Virginia Chronicle home page (browser-only; Cloudflare blocks machine access).")
440
+ @click.option("--land", is_flag=True, help="Land Office patents/grants: libguide + LONN volume index.")
441
+ @click.option("--arvas", is_flag=True, help="ARVAS finding-aid search home (browser-only).")
442
+ @click.option("--chancery", is_flag=True, help="Chancery Records Index home page.")
443
+ def cmd_url(chancery_case, catalog_query, chronicle, land, arvas, chancery) -> None:
444
+ """Print verified portal URLs (no search is run)."""
445
+ if chancery_case:
446
+ click.echo(CHANCERY_DETAIL + "?CFN=" + chancery_case)
447
+ if catalog_query:
448
+ click.echo(PRIMO_BASE + "/discovery/search?vid=" + quote(PRIMO_VID, safe="") +
449
+ "&query=any,contains," + quote(catalog_query) + "&lang=en")
450
+ if chancery:
451
+ click.echo("https://www.lva.virginia.gov/collections/chancery")
452
+ click.echo(CHANCERY_BASE + "/")
453
+ if chronicle:
454
+ click.echo("https://www.virginiachronicle.com/ (free; search in the browser -- Cloudflare blocks curl/headless Chromium, verified 2026-11-24)")
455
+ if land:
456
+ click.echo("https://lva-virginia.libguides.com/land-grants")
457
+ click.echo("https://image.lva.virginia.gov/LONN/LO.html (Virginia Land Office Patents and Grants Index, browse by volume)")
458
+ if arvas:
459
+ click.echo("https://arvasarchive.org/ (browser-only; plain HTTP returns an empty 202, verified 2026-11-24)")
460
+ if not any([chancery_case, catalog_query, chronicle, land, arvas, chancery]):
461
+ click.echo("https://www.lva.virginia.gov/collections")
462
+ click.echo("https://www.lva.virginia.gov/collections/digital-collections")
463
+
464
+
465
+ if __name__ == "__main__":
466
+ cli()
@@ -0,0 +1,148 @@
1
+ ---
2
+ name: wikitree
3
+ description: Search and read public WikiTree profiles via the bundled uv-based `wikitree` CLI and the public WikiTree API (api.wikitree.com), plus WikiTree One Name Study pages on the website. Covers profile lookup, person search, ancestors, and biographies, plus citation and evidence rules. Use when looking up a WikiTree profile, tracing an ancestral line, checking what WikiTree says about a person, or finding the sources a profile cites. No account or key needed for public profiles.
4
+ ---
5
+
6
+ # WikiTree
7
+
8
+ This skill includes a standalone executable Python CLI at
9
+ `skills/wikitree/scripts/wikitree` using a PEP 723
10
+ `#!/usr/bin/env -S uv run --script` shebang with inline dependencies
11
+ (`click`, `httpx`). No virtualenv setup or API key is required for public
12
+ profiles.
13
+
14
+ - **Public profiles:** no authentication, no key. Only public profiles are
15
+ returned; private profiles come back privacy-limited.
16
+ - **Private profiles:** need a WikiTree member login via the API's
17
+ `clientLogin` flow (multi-step, user goes to WikiTree.com and returns
18
+ with a token). The CLI does not implement login; see "API reference"
19
+ below.
20
+
21
+ ## Bundled CLI (`scripts/wikitree`)
22
+
23
+ Path: `skills/wikitree/scripts/wikitree`
24
+
25
+ ### Search for people
26
+
27
+ ```bash
28
+ # Search public profiles by first and last name
29
+ skills/wikitree/scripts/wikitree search --first Abraham --last Lincoln
30
+
31
+ # Same search, raw JSON
32
+ skills/wikitree/scripts/wikitree search --first Abraham --last Lincoln --limit 5 --json
33
+
34
+ # Narrow by birth location
35
+ skills/wikitree/scripts/wikitree search --last Barton --birth-location "Massachusetts" --limit 10
36
+
37
+ # Require dates on matches (otherwise dateless profiles are also returned)
38
+ skills/wikitree/scripts/wikitree search --first Clara --last Barton --date-include both
39
+ ```
40
+
41
+ ### Look up one profile
42
+
43
+ ```bash
44
+ # By WikiTree ID (<Surname>-<Number> from search output)
45
+ skills/wikitree/scripts/wikitree person <WikiTree-ID>
46
+
47
+ # Raw JSON, all fields
48
+ skills/wikitree/scripts/wikitree person <WikiTree-ID> --fields '*' --json
49
+
50
+ # By numeric user Id
51
+ skills/wikitree/scripts/wikitree person <numeric-id>
52
+ ```
53
+
54
+ ### Ancestors and biography
55
+
56
+ ```bash
57
+ # Two generations of ancestors
58
+ skills/wikitree/scripts/wikitree ancestors <WikiTree-ID> --depth 2
59
+
60
+ # Biography text (wiki markup) for a profile
61
+ skills/wikitree/scripts/wikitree bio <WikiTree-ID>
62
+
63
+ # Biography as HTML instead
64
+ skills/wikitree/scripts/wikitree bio <WikiTree-ID> --format html
65
+ ```
66
+
67
+ ### Environment variables
68
+
69
+ - `WIKITREE_APP_ID`: application id sent with every API call (default
70
+ `Kinloom`). WikiTree asks every client to send one; calls without an id
71
+ are subject to strict rate limits.
72
+
73
+ ## API reference (verified live 2026-11-24)
74
+
75
+ - Base: `GET https://api.wikitree.com/api.php` (GET or POST, JSON out).
76
+ Docs: `https://github.com/wikitree/wikitree-api` (README plus one
77
+ `.md` file per action).
78
+ - Auth: none for public profiles. Privacy-limited data for private ones.
79
+ - Response shape: a JSON array; each element has `status` (0 or `""` = ok,
80
+ or an error string such as `"Illegal WikiTree ID"`) and the requested
81
+ data.
82
+ - Dates use `YYYY-MM-DD` with `00` for unknown month/day;
83
+ `0000-00-00` means no date at all.
84
+
85
+ | Action | Use | Key params |
86
+ | --- | --- | --- |
87
+ | `getPerson` | One person by WikiTree ID or numeric Id | `key`, `fields`, `bioFormat` (wiki/html/both), `resolveRedirect` (1 = follow redirects) |
88
+ | `getProfile` | Person or Free-Space profile by WikiTree ID or PageId | `key`, `fields` |
89
+ | `searchPerson` | Search like Special:SearchPerson | `FirstName`, `LastName`, `BirthDate`, `DeathDate`, `BirthLocation`, `DeathLocation`, `Gender`, `fatherFirstName`, `fatherLastName`, `motherFirstName`, `motherLastName`, `dateInclude` (both/neither), `dateSpread` (1-20), `lastNameMatch` (all/current/birth/strict), `skipVariants` (1), `sort`, `limit` (1-100, default 10), `start`, `fields` |
90
+ | `getAncestors` | DEPRECATED: the API errors and directs callers to `getPeople` with `ancestors=N` instead. Do not use. | — |
91
+ | `getDescendants` | Descendants following children (still works, verified 2026-11-24) | `key`, `depth`, `fields` |
92
+ | `getRelatives` | Parents, children, siblings, spouses | `keys`, `getParents`, `getChildren`, `getSpouses`, `getSiblings`, `fields` |
93
+ | `getBio` | Biography text for a profile | `key`, `bioFormat` |
94
+ | `getPhotos` | Photos connected to a profile | `key` |
95
+ | `getCategories` | Categories connected to a profile | `key` |
96
+ | `getPeople` | Several profiles by key and/or relationship; also the replacement for `getAncestors` via `ancestors=N` (max 25) and for descendants via `descendants=N` (max 10) | `keys`, `fields`, `ancestors`, `descendants`, `nuclear`, `minGeneration`, `limit`, `start` |
97
+ | `clientLogin` | Authenticate as a member (private profiles) | multi-step token flow, see docs |
98
+
99
+ Default `getPerson` fields are all fields except biography, children and
100
+ spouses; `fields=*` returns everything. The `Mother` and `Father` fields
101
+ hold numeric user Ids; follow them with `getPerson` by Id.
102
+
103
+ ### API behavior notes (verified live 2026-11-24)
104
+
105
+ - Some matches returned by `searchPerson` contain only `Id` and `index`
106
+ (sparse matches); follow up with `person <Id>` for the full profile.
107
+ - `getPeople` returns `status: ""` (empty string) on success rather than
108
+ `0`; the CLI accepts both `0` and `""`.
109
+ - The legacy `getAncestors` action returns a deprecation error directing
110
+ callers to `getPeople` with `ancestors=N`; the CLI's `ancestors` command
111
+ already uses `getPeople`.
112
+
113
+ ## One Name Studies (website)
114
+
115
+ - WikiTree hosts surname-level collaborative projects called One Name
116
+ Studies at `https://www.wikitree.com/wiki/Space:<Surname>_Name_Study`
117
+ and `https://www.wikitree.com/wiki/Project:One_Name_Studies`.
118
+ - Profiles participating in a study carry a `{{One Name Study|name=<Surname>}}`
119
+ sticker and a matching surname study category.
120
+ - Website note: `wikitree.com` profile and space pages can return a WAF
121
+ challenge (HTTP 202, empty body) to plain curl, so read website pages
122
+ through a browser, not curl. The API at `api.wikitree.com` is unaffected
123
+ and answers direct HTTP requests.
124
+
125
+ ## Rules and limits
126
+
127
+ - **WikiTree is a lead, not evidence.** Profiles are collaborative and
128
+ user-contributed; a profile states what other researchers believe, not
129
+ what a record proves. Always follow the profile's cited sources, and
130
+ cross-check against primary records before recording conclusions in
131
+ `data/`. Never copy a WikiTree parentage claim without its citation.
132
+ - **Pre-1700 lines need primary citations.** Pre-1700 profiles in
133
+ particular are expected to cite primary sources. If a profile's only
134
+ sources are compiled genealogies, treat the claim as secondary and look
135
+ for the underlying record.
136
+ - **Document conflicting claims.** WikiTree profiles record disputes in
137
+ Research Notes. When two researchers disagree on parentage or dates,
138
+ keep both claims and their reasoning; do not pick a winner silently.
139
+ - **Living people are excluded** from public search results. Do not try
140
+ to retrieve them through the API.
141
+ - **Rate limits:** WikiTree subjects calls without an `appId` to strict
142
+ rate limits. The CLI always sends one. Keep calls to about one per
143
+ second and do not batch hundreds of lookups in a loop without a pause.
144
+ - **Do not edit through the API.** The API is read-only; edits go
145
+ through the website by a logged-in member. The CLI never writes.
146
+ - **Redirects:** merged profiles redirect to a surviving WikiTree ID.
147
+ Pass `--resolve-redirect` (person) or `resolveRedirect=1` so a lookup
148
+ follows the merge instead of returning the redirect stub.