@kinloom/cli 0.2.0 → 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 (80) hide show
  1. package/dist/assets/cached-ocr.py +346 -116
  2. package/dist/assets/ocr.md +25 -1
  3. package/dist/assets/prep-scan.md +42 -4
  4. package/dist/assets/prep-scan.py +432 -10
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
  7. package/dist/bundled-skills/archive-org/SKILL.md +40 -7
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
  9. package/dist/bundled-skills/california-archives/SKILL.md +10 -0
  10. package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
  11. package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
  12. package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
  13. package/dist/bundled-skills/findagrave/SKILL.md +18 -5
  14. package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
  15. package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
  16. package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
  17. package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
  18. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
  19. package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
  20. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
  21. package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
  22. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
  23. package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
  24. package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
  25. package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
  26. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
  27. package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
  28. package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
  29. package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
  30. package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
  31. package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
  32. package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
  33. package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
  34. package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
  35. package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
  36. package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
  37. package/dist/bundled-skills/wikitree/SKILL.md +7 -1
  38. package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +107 -2
  41. package/dist/cli.js.map +1 -1
  42. package/dist/client.d.ts.map +1 -1
  43. package/dist/client.js +30 -5
  44. package/dist/client.js.map +1 -1
  45. package/dist/commands/ops/audit.d.ts.map +1 -1
  46. package/dist/commands/ops/audit.js +5 -0
  47. package/dist/commands/ops/audit.js.map +1 -1
  48. package/dist/commands/ops/dates.d.ts +87 -0
  49. package/dist/commands/ops/dates.d.ts.map +1 -0
  50. package/dist/commands/ops/dates.js +228 -0
  51. package/dist/commands/ops/dates.js.map +1 -0
  52. package/dist/commands/ops/help.d.ts +3 -1
  53. package/dist/commands/ops/help.d.ts.map +1 -1
  54. package/dist/commands/ops/help.js +33 -0
  55. package/dist/commands/ops/help.js.map +1 -1
  56. package/dist/commands/ops/index.d.ts +3 -1
  57. package/dist/commands/ops/index.d.ts.map +1 -1
  58. package/dist/commands/ops/index.js +2 -0
  59. package/dist/commands/ops/index.js.map +1 -1
  60. package/dist/commands/ops/integrate.d.ts +5 -0
  61. package/dist/commands/ops/integrate.d.ts.map +1 -1
  62. package/dist/commands/ops/integrate.js +217 -26
  63. package/dist/commands/ops/integrate.js.map +1 -1
  64. package/dist/commands/ops/sync.d.ts +17 -0
  65. package/dist/commands/ops/sync.d.ts.map +1 -1
  66. package/dist/commands/ops/sync.js +173 -0
  67. package/dist/commands/ops/sync.js.map +1 -1
  68. package/dist/commands/ops/verify.d.ts +76 -0
  69. package/dist/commands/ops/verify.d.ts.map +1 -0
  70. package/dist/commands/ops/verify.js +325 -0
  71. package/dist/commands/ops/verify.js.map +1 -0
  72. package/dist/commands/records/index.d.ts +1 -1
  73. package/dist/commands/records/index.d.ts.map +1 -1
  74. package/dist/commands/records/index.js +1 -1
  75. package/dist/commands/records/index.js.map +1 -1
  76. package/dist/commands/records/runner.d.ts +2 -0
  77. package/dist/commands/records/runner.d.ts.map +1 -1
  78. package/dist/commands/records/runner.js +33 -2
  79. package/dist/commands/records/runner.js.map +1 -1
  80. package/package.json +2 -2
@@ -16,12 +16,17 @@ This CLI downloads the USGS per-state pipe-delimited text files
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ from contextlib import contextmanager
20
+ import hashlib
19
21
  import json
22
+ import math
20
23
  import os
21
24
  import sys
25
+ import time
22
26
  import zipfile
23
27
  from io import BytesIO
24
28
  from pathlib import Path
29
+ from typing import Any, Iterator
25
30
 
26
31
  import click
27
32
  import httpx
@@ -30,6 +35,7 @@ S3_BASE = "https://prd-tnm.s3.amazonaws.com/StagedProducts/GeographicNames"
30
35
  SEARCH_APP = "https://edits.nationalmap.gov/apps/gaz-domestic/public/search/names"
31
36
  HEADERS = {"User-Agent": "kinloom/1.0 (genealogy research)"}
32
37
  TIMEOUT = 120.0
38
+ DEFAULT_QUERY_TTL_HOURS = 720.0
33
39
 
34
40
  STATE_CODES = {
35
41
  "AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
@@ -41,12 +47,128 @@ STATE_CODES = {
41
47
 
42
48
 
43
49
  def cache_dir() -> Path:
44
- override = os.environ.get("GNIS_CACHE_DIR")
50
+ override = os.environ.get("KINLOOM_GNIS_CACHE_DIR") or os.environ.get("GNIS_CACHE_DIR")
45
51
  if override:
46
52
  return Path(override).expanduser()
47
53
  return Path.home() / ".cache" / "kinloom-gnis"
48
54
 
49
55
 
56
+ def resolve_query_ttl_hours(cli_ttl: float | None) -> float:
57
+ if cli_ttl is not None:
58
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
59
+ raise click.BadParameter(
60
+ f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0)."
61
+ )
62
+ return float(cli_ttl)
63
+ raw = os.environ.get("KINLOOM_GNIS_QUERY_TTL_HOURS")
64
+ if raw is not None and raw.strip():
65
+ try:
66
+ parsed = float(raw.strip())
67
+ except ValueError as exc:
68
+ raise click.BadParameter(
69
+ f"Invalid KINLOOM_GNIS_QUERY_TTL_HOURS value: {raw!r}."
70
+ ) from exc
71
+ if not math.isfinite(parsed) or parsed < 0:
72
+ raise click.BadParameter(
73
+ f"Invalid KINLOOM_GNIS_QUERY_TTL_HOURS value: {raw!r} (must be >= 0)."
74
+ )
75
+ return parsed
76
+ return DEFAULT_QUERY_TTL_HOURS
77
+
78
+
79
+ def resolve_safe_child(root: Path, filename: str) -> Path:
80
+ if (
81
+ not filename
82
+ or "\x00" in filename
83
+ or "/" in filename
84
+ or "\\" in filename
85
+ or ":" in filename
86
+ or filename in (".", "..")
87
+ ):
88
+ raise ValueError(f"Unsafe filename: {filename!r}")
89
+ root_resolved = root.resolve()
90
+ dest = (root_resolved / filename).resolve()
91
+ if dest == root_resolved or not dest.is_relative_to(root_resolved):
92
+ raise ValueError(f"Unsafe path escaping root: {filename!r}")
93
+ return dest
94
+
95
+
96
+ @contextmanager
97
+ def file_lock(lock_path: Path) -> Iterator[None]:
98
+ """Advisory exclusive file lock (POSIX flock) with safe fallback on non-POSIX."""
99
+ try:
100
+ import fcntl
101
+ except ImportError:
102
+ yield
103
+ return
104
+
105
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
106
+ with open(lock_path, "a+b") as lock_file:
107
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
108
+ try:
109
+ yield
110
+ finally:
111
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
112
+
113
+
114
+ def read_json_if_valid(path: Path) -> dict[str, Any] | None:
115
+ if not path.is_file():
116
+ return None
117
+ try:
118
+ parsed = json.loads(path.read_text(encoding="utf-8"))
119
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
120
+ return None
121
+ return parsed if isinstance(parsed, dict) else None
122
+
123
+
124
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
125
+ dest.parent.mkdir(parents=True, exist_ok=True)
126
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
127
+ try:
128
+ tmp.write_bytes(data)
129
+ os.replace(tmp, dest)
130
+ except Exception:
131
+ tmp.unlink(missing_ok=True)
132
+ raise
133
+
134
+
135
+ def atomic_write_text(dest: Path, text: str) -> None:
136
+ atomic_write_bytes(dest, text.encode("utf-8"))
137
+
138
+
139
+ def atomic_write_json(dest: Path, payload: Any) -> None:
140
+ atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
141
+
142
+
143
+ def query_cache_path(canonical_params: dict[str, Any], cdir: Path) -> tuple[str, Path]:
144
+ canonical = json.dumps(
145
+ canonical_params, sort_keys=True, separators=(",", ":"), ensure_ascii=False
146
+ )
147
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
148
+ return digest, resolve_safe_child(cdir / "_queries", f"{digest}.json")
149
+
150
+
151
+ def _read_cached_search(
152
+ canonical_params: dict[str, Any], *, cdir: Path, ttl_hours: float
153
+ ) -> dict[str, Any] | None:
154
+ ttl_seconds = ttl_hours * 3600.0
155
+ if ttl_seconds <= 0:
156
+ return None
157
+ _, path = query_cache_path(canonical_params, cdir)
158
+ envelope = read_json_if_valid(path)
159
+ if envelope is None:
160
+ return None
161
+ cached_at = envelope.get("cached_at")
162
+ data = envelope.get("data")
163
+ if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
164
+ return None
165
+ if not isinstance(data.get("results"), list):
166
+ return None
167
+ if (time.time() - float(cached_at)) <= ttl_seconds:
168
+ return data
169
+ return None
170
+
171
+
50
172
  def _state_zip_url(state: str) -> str:
51
173
  return f"{S3_BASE}/DomesticNames/DomesticNames_{state}_Text.zip"
52
174
 
@@ -86,33 +208,41 @@ def _load_rows(path: Path) -> list[dict]:
86
208
  return rows
87
209
 
88
210
 
89
- def _ensure_state_file(state: str) -> Path:
211
+ def _ensure_state_file(state: str, *, refresh: bool = False) -> Path:
90
212
  state = state.upper()
91
213
  if state not in STATE_CODES:
92
214
  raise click.ClickException(f"Unknown state/territory code: {state}")
93
215
  cdir = cache_dir()
94
216
  cdir.mkdir(parents=True, exist_ok=True)
95
- path = cdir / f"{state}.txt"
96
- if path.exists():
217
+ path = resolve_safe_child(cdir, f"{state}.txt")
218
+ if path.exists() and not refresh:
219
+ return path
220
+ lock_path = resolve_safe_child(cdir / "_locks", f"state_{state}.lock")
221
+ with file_lock(lock_path):
222
+ if path.exists() and not refresh:
223
+ return path
224
+ click.echo(f"Downloading GNIS data for {state} ...", err=True)
225
+ _, text = _extract_txt(_download_zip(_state_zip_url(state)))
226
+ atomic_write_text(path, text)
227
+ click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
97
228
  return path
98
- click.echo(f"Downloading GNIS data for {state} ...", err=True)
99
- _, text = _extract_txt(_download_zip(_state_zip_url(state)))
100
- path.write_text(text, encoding="utf-8")
101
- click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
102
- return path
103
229
 
104
230
 
105
- def _ensure_historical_file() -> Path:
231
+ def _ensure_historical_file(*, refresh: bool = False) -> Path:
106
232
  cdir = cache_dir()
107
233
  cdir.mkdir(parents=True, exist_ok=True)
108
- path = cdir / "HistoricalFeatures.txt"
109
- if path.exists():
234
+ path = resolve_safe_child(cdir, "HistoricalFeatures.txt")
235
+ if path.exists() and not refresh:
236
+ return path
237
+ lock_path = resolve_safe_child(cdir / "_locks", "historical.lock")
238
+ with file_lock(lock_path):
239
+ if path.exists() and not refresh:
240
+ return path
241
+ click.echo("Downloading national Historical Features file (large) ...", err=True)
242
+ _, text = _extract_txt(_download_zip(_historical_zip_url()))
243
+ atomic_write_text(path, text)
244
+ click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
110
245
  return path
111
- click.echo("Downloading national Historical Features file (large) ...", err=True)
112
- _, text = _extract_txt(_download_zip(_historical_zip_url()))
113
- path.write_text(text, encoding="utf-8")
114
- click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
115
- return path
116
246
 
117
247
 
118
248
  def _compact(row: dict) -> dict:
@@ -156,26 +286,18 @@ def cli() -> None:
156
286
 
157
287
  @cli.command()
158
288
  @click.argument("state")
159
- @click.option("--force", is_flag=True, help="Re-download even if cached.")
289
+ @click.option("--force", "--refresh", "force", is_flag=True, help="Re-download even if cached.")
160
290
  def download(state, force):
161
291
  """Download and cache the GNIS text file for a state (e.g. MI, CA, MO)."""
162
292
  state = state.upper()
163
293
  if state not in STATE_CODES:
164
294
  raise click.ClickException(f"Unknown state/territory code: {state}")
165
- path = cache_dir() / f"{state}.txt"
295
+ path = resolve_safe_child(cache_dir(), f"{state}.txt")
166
296
  if path.exists() and not force:
167
297
  rows = _load_rows(path)
168
- click.echo(f"Already cached: {path} ({len(rows)} features). Use --force to re-download.")
169
- return
170
- path = _ensure_state_file(state) if not force else None
171
- if force:
172
- cdir = cache_dir()
173
- cdir.mkdir(parents=True, exist_ok=True)
174
- _, text = _extract_txt(_download_zip(_state_zip_url(state)))
175
- path = cdir / f"{state}.txt"
176
- path.write_text(text, encoding="utf-8")
177
- click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)")
298
+ click.echo(f"Already cached: {path} ({len(rows)} features). Use --force or --refresh to re-download.")
178
299
  return
300
+ path = _ensure_state_file(state, refresh=force)
179
301
  rows = _load_rows(path)
180
302
  click.echo(f"Cached {path} ({len(rows)} features)")
181
303
 
@@ -190,26 +312,67 @@ def download(state, force):
190
312
  @click.option("--historical", is_flag=True,
191
313
  help="Search the national Historical Features file instead of a state file (defunct places, post offices).")
192
314
  @click.option("--limit", "-n", default=20, show_default=True)
315
+ @click.option("--refresh", is_flag=True,
316
+ help="Bypass cached query and state data and re-download fresh GNIS data.")
317
+ @click.option("--cache-ttl-hours", type=float, default=None,
318
+ help="Override query cache TTL in hours (default: 720 or $KINLOOM_GNIS_QUERY_TTL_HOURS).")
193
319
  @click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of compact text.")
194
- def search(name, state, exact, feature_class, county, historical, limit, as_json):
320
+ def search(name, state, exact, feature_class, county, historical, limit, refresh, cache_ttl_hours, as_json):
195
321
  """Search feature names (substring unless --exact)."""
196
- if historical:
197
- rows = _load_rows(_ensure_historical_file())
198
- source = "HistoricalFeatures (national)"
199
- else:
322
+ ttl_hours = resolve_query_ttl_hours(cache_ttl_hours)
323
+ normalized_state: str | None = None
324
+ if not historical:
200
325
  if not state:
201
326
  raise click.UsageError("Give --state (e.g. --state CA) or --historical.")
202
- rows = _load_rows(_ensure_state_file(state))
203
- source = f"DomesticNames_{state.upper()}"
204
- matches = _match(rows, name, exact, feature_class, county)[:limit]
327
+ normalized_state = state.upper()
328
+ if normalized_state not in STATE_CODES:
329
+ raise click.ClickException(f"Unknown state/territory code: {normalized_state}")
330
+
331
+ cdir = cache_dir()
332
+ canonical_params: dict[str, Any] = {
333
+ "name": name,
334
+ "state": None if historical else normalized_state,
335
+ "exact": bool(exact),
336
+ "feature_class": feature_class,
337
+ "county": county,
338
+ "historical": bool(historical),
339
+ "limit": int(limit),
340
+ }
341
+
342
+ payload: dict[str, Any] | None = None
343
+ if not refresh:
344
+ payload = _read_cached_search(canonical_params, cdir=cdir, ttl_hours=ttl_hours)
345
+
346
+ if payload is None:
347
+ digest, cache_path = query_cache_path(canonical_params, cdir)
348
+ lock_path = resolve_safe_child(cdir / "_locks", f"query_{digest}.lock")
349
+ with file_lock(lock_path):
350
+ if not refresh:
351
+ payload = _read_cached_search(canonical_params, cdir=cdir, ttl_hours=ttl_hours)
352
+ if payload is None:
353
+ if historical:
354
+ rows = _load_rows(_ensure_historical_file(refresh=refresh))
355
+ source = "HistoricalFeatures (national)"
356
+ else:
357
+ assert normalized_state is not None
358
+ rows = _load_rows(_ensure_state_file(normalized_state, refresh=refresh))
359
+ source = f"DomesticNames_{normalized_state}"
360
+ matches = _match(rows, name, exact, feature_class, county)[:limit]
361
+ payload = {
362
+ "source": source,
363
+ "matches": len(matches),
364
+ "results": [_compact(r) for r in matches],
365
+ }
366
+ atomic_write_json(
367
+ cache_path,
368
+ {"cached_at": time.time(), "params": canonical_params, "data": payload},
369
+ )
370
+
205
371
  if as_json:
206
- click.echo(json.dumps(
207
- {"source": source, "matches": len(matches),
208
- "results": [_compact(r) for r in matches]}, indent=2, ensure_ascii=False))
372
+ click.echo(json.dumps(payload, indent=2, ensure_ascii=False))
209
373
  return
210
- click.echo(f"source: {source} | matches shown: {len(matches)}")
211
- for row in matches:
212
- c = _compact(row)
374
+ click.echo(f"source: {payload['source']} | matches shown: {payload['matches']}")
375
+ for c in payload["results"]:
213
376
  click.echo(f"- {c['feature_id']} | {c['feature_name']} ({c['feature_class']}) | "
214
377
  f"{c['county']} County, {c['state']} | {c['latitude']}, {c['longitude']} | map: {c['map_name']}")
215
378
 
@@ -218,15 +381,16 @@ def search(name, state, exact, feature_class, county, historical, limit, as_json
218
381
  @click.argument("feature_id")
219
382
  @click.option("--state", "-s", default=None, help="State code (downloads and caches if needed).")
220
383
  @click.option("--historical", is_flag=True, help="Look in the national Historical Features file.")
384
+ @click.option("--refresh", is_flag=True, help="Re-download the underlying GNIS file before lookup.")
221
385
  @click.option("--json", "as_json", is_flag=True)
222
- def get(feature_id, state, historical, as_json):
386
+ def get(feature_id, state, historical, refresh, as_json):
223
387
  """Show one feature by its GNIS feature_id."""
224
388
  if historical:
225
- rows = _load_rows(_ensure_historical_file())
389
+ rows = _load_rows(_ensure_historical_file(refresh=refresh))
226
390
  else:
227
391
  if not state:
228
392
  raise click.UsageError("Give --state or --historical.")
229
- rows = _load_rows(_ensure_state_file(state))
393
+ rows = _load_rows(_ensure_state_file(state, refresh=refresh))
230
394
  for row in rows:
231
395
  if (row.get("feature_id") or "") == str(feature_id):
232
396
  if as_json:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: virginia-archives
3
- description: Research historical and genealogical records at the Library of Virginia via the bundled `va-archives` CLI: Chancery Records Index search, case detail, and scanned-page download, plus the public Primo catalog API. Also covers Virginia Chronicle newspapers, Land Office patents and grants, Virginia Untold, and ARVAS finding aids, with an honest note on which of those are browser-only. Use when tracing ancestors through Virginia, finding chancery causes, land patents, newspaper notices, or catalog records held by the Library of Virginia, or deciding whether a Virginia record is online, orderable, or visit-only.
3
+ description: Research historical and genealogical records at the Library of Virginia via the bundled `va-archives` CLI: Chancery Records Index search, case detail, and scanned-page download, plus the public Primo catalog API, Land Office and Dunmore's War TIFF scans from image.lva.virginia.gov, and Rosetta (IE id) file downloads, all disk-cached. Also covers Virginia Chronicle newspapers, Land Office patents and grants, Virginia Untold, and ARVAS finding aids, with an honest note on which of those are browser-only. Use when tracing ancestors through Virginia, finding chancery causes, land patents, newspaper notices, or catalog records held by the Library of Virginia, or deciding whether a Virginia record is online, orderable, or visit-only.
4
4
  ---
5
5
 
6
6
  # Virginia Archives: Library of Virginia
@@ -15,7 +15,7 @@ The Library of Virginia is both the state library and the state archives. It hol
15
15
 
16
16
  Path: `skills/virginia-archives/scripts/va-archives`
17
17
 
18
- A standalone executable Python CLI with a PEP 723 `#!/usr/bin/env -S uv run --script` shebang and inline dependencies (`click`, `httpx`). No virtualenv setup, no API key, no account. Run it from the repo root, e.g. `skills/virginia-archives/scripts/va-archives chancery search Lincoln`.
18
+ A standalone executable Python CLI with a PEP 723 `#!/usr/bin/env -S uv run --script` shebang and inline dependencies (`click`, `httpx`, `pillow`). No virtualenv setup, no API key, no account. Run it from the repo root, e.g. `skills/virginia-archives/scripts/va-archives chancery search Lincoln`.
19
19
 
20
20
  The Library of Virginia exposes real machine interfaces, verified live on 2026-11-24 (see Verification log). The CLI uses plain HTTP for everything it does; no browser automation is bundled.
21
21
 
@@ -60,6 +60,45 @@ skills/virginia-archives/scripts/va-archives url --catalog Lincoln
60
60
  skills/virginia-archives/scripts/va-archives url --chronicle --land --arvas
61
61
  ```
62
62
 
63
+ ### Image server scans: `grant-tif` (alias `lva-tif`) and `dunmore`
64
+
65
+ ```bash
66
+ # One Land Office patent/grant page (raw TIFF, or JPEG when --out ends in .jpg/.jpeg)
67
+ skills/virginia-archives/scripts/va-archives grant-tif /LONN/LO-3/372/372_0195.tif --out patent.tif
68
+ skills/virginia-archives/scripts/va-archives lva-tif https://image.lva.virginia.gov/LONN/LO-3/372/372_0195.tif --out patent.jpg
69
+
70
+ # Dunmore's War (1774) card -> neighbouring page TIFFs; save the card's page (or --page N)
71
+ skills/virginia-archives/scripts/va-archives dunmore <DRAWER> <CARD>
72
+ skills/virginia-archives/scripts/va-archives dunmore <DRAWER> <CARD> --page 100 --out dw-page100.jpg --json
73
+ ```
74
+
75
+ `grant-tif` fetches a single scan from `image.lva.virginia.gov` only. It accepts a full `https://image.lva.virginia.gov/...` URL or a path on that host, and it rejects any other host or scheme (including plain `http://`), credentials, ports, query strings, `.`/`..` segments (raw or percent-encoded), backslashes, and non-image suffixes. If the server redirects to another host, the download is refused. `--out *.jpg` converts TIFF to JPEG when Pillow is importable; Pillow is in the script's inline dependencies, so it is available under `uv run`. Without Pillow, the raw TIFF is written next to the requested file with a `.tif` suffix. Any other suffix gets the raw bytes. Land Office TIFF links appear in Primo catalog records (`catalog <surname> --json`).
76
+
77
+ `dunmore DRAWER CARD` takes the `dir` and `card` values from the catalog's `GetDW.pl?dir=<dddd>/W<dddd>&card=<n>` links (Dunmore's War payroll and service-claim index cards). The CGI redirects to a `/cgi-bin/drawer` page that lists neighbouring microfilm page TIFFs under `/Microfilm/DW/<reel>/<nnnnn>.tif`. The command lists those pages and marks the card's own page, which is the link with no "Page N" label. `--out` saves the card's page, or the page chosen with `--page N`, through the same validated, cached download as `grant-tif`.
78
+
79
+ ### Rosetta delivered files: `download-rosetta`
80
+
81
+ ```bash
82
+ skills/virginia-archives/scripts/va-archives download-rosetta IE3453061 --list
83
+ skills/virginia-archives/scripts/va-archives download-rosetta IE3453061 --out item.pdf # viewer's initial file
84
+ skills/virginia-archives/scripts/va-archives download-rosetta IE3453061 --file 2 --json # e.g. the Transcription
85
+ skills/virginia-archives/scripts/va-archives download-rosetta IE3453061 --fl FL3453067
86
+ ```
87
+
88
+ The Library's digital objects live in Ex Libris Rosetta at `rosetta.virginiamemory.com`. Primo records link them as `DeliveryManagerServlet?dps_pid=IE<n>`. The command validates the id with `^IE\d+$` and keeps a single cookie session while it resolves the item. It reads the delivery page's `ieViewer.do` iframe (with its `dps_dvs` token), takes the `FL<n>` file pids and their METS titles from the viewer, and streams the chosen file from `DeliveryManagerServlet?dps_pid=FL<n>&dps_func=stream`. Every hop must stay on `https://rosetta.virginiamemory.com`. If the server returns an HTML page instead of a file, the command treats the item as restricted. The output name defaults to `<IE>_<FL>.<ext>`, with the extension taken from the content type.
89
+
90
+ ### Disk cache
91
+
92
+ Every network response is cached under `$KINLOOM_VA_ARCHIVES_CACHE_DIR`. The default is `$XDG_CACHE_HOME/kinloom-va-archives`, or `~/.cache/kinloom-va-archives` when `XDG_CACHE_HOME` is unset. Writes go to a temp file that is then renamed into place, under a per-entry `fcntl.flock`.
93
+
94
+ - `http/`: chancery search/case/images/localities HTML and catalog JSON, keyed by a SHA-256 of the request. These expire after `$KINLOOM_VA_ARCHIVES_TTL_HOURS` (default 168).
95
+ - `files/`: chancery page PDFs, ZIPs, and image-server TIFFs, keyed by URL. These never expire.
96
+ - `rosetta/<IE>/`: `files.json` (the resolved file list) and `<FL>.bin` (the delivered bytes), keyed by IE id.
97
+
98
+ To refetch, put `--refresh` before the subcommand to cover the whole run (`va-archives --refresh chancery localities`), or add it to a single command (`grant-tif ... --refresh`).
99
+
100
+ Tests: `uv run --with click --with httpx python3 -m unittest skills/virginia-archives/tests/test_va_archives.py`. These are mocked-HTTP tests with synthetic fixtures. Vitest also runs them in `packages/cli/src/commands/records/records.test.ts`.
101
+
63
102
  ## What is searchable online
64
103
 
65
104
  - **Chancery Records Index:** https://www.lva.virginia.gov/collections/chancery (search itself lives at https://old.lva.virginia.gov/chancery/). See CLI above. Individual case pages use the verified pattern `case_detail.asp?CFN=<locality-code>-<year>-<number>`.
@@ -96,6 +135,7 @@ Worked order for tracing a family through Virginia (for example before a westwar
96
135
  - Virginia Chronicle: curl 403 with Cloudflare "Just a moment..."; headless Chromium also returns the challenge page. Browser-only.
97
136
  - ARVAS: plain HTTP returns 202 with an empty body. Browser-only.
98
137
  - LONN volume index `image.lva.virginia.gov/LONN/LO.html`: 200, browse-by-volume table; its Aleph name-search host was unreachable (connection failed).
138
+ - Image server and Rosetta (verified 2026-11-26): `image.lva.virginia.gov/LONN/LO-3/372/372_0195.tif` returns `image/tiff` (CCITT G4). `cgi-bin/GetDW.pl?dir=<DRAWER>&card=<CARD>` redirects to a `cgi-bin/drawer` page listing `/Microfilm/DW/001/*.tif` pages. `rosetta.virginiamemory.com/delivery/DeliveryManagerServlet?dps_pid=IE3453061` embeds `view/action/ieViewer.do?...dps_dvs=...`, which lists `FL3453066` (Original) and `FL3453067` (Transcription). Both stream as `application/pdf` via `dps_func=stream`.
99
139
  - No account or API key is needed for anything the CLI does. Fees apply only to ordering copies, noted per collection above.
100
140
 
101
141
  ## What this skill does not cover