@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
@@ -27,16 +27,154 @@ verified GET search URL. Use the `mdh` command for the browser path.
27
27
 
28
28
  from __future__ import annotations
29
29
 
30
+ import hashlib
30
31
  import json
32
+ import math
33
+ import os
31
34
  import re
32
35
  import sys
36
+ import time
37
+ from contextlib import contextmanager
33
38
  from html.parser import HTMLParser
34
39
  from pathlib import Path
40
+ from typing import Any, Callable, Iterator
35
41
  from urllib.parse import urljoin
36
42
 
37
43
  import click
38
44
  import httpx
39
45
 
46
+ DEFAULT_CACHE_TTL_HOURS = 168.0
47
+ CACHE_SCHEMA = 1
48
+
49
+
50
+ def cache_dir() -> Path:
51
+ override = os.environ.get("KINLOOM_MO_ARCHIVES_CACHE_DIR")
52
+ if override:
53
+ return Path(override).expanduser()
54
+ return Path.home() / ".cache" / "kinloom-mo-archives"
55
+
56
+
57
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
58
+ if cli_ttl is not None:
59
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
60
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
61
+ return float(cli_ttl)
62
+ raw = os.environ.get("KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS")
63
+ if raw is not None and raw.strip():
64
+ try:
65
+ parsed = float(raw.strip())
66
+ except ValueError as exc:
67
+ raise click.BadParameter(f"Invalid KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
68
+ if not math.isfinite(parsed) or parsed < 0:
69
+ raise click.BadParameter(
70
+ f"Invalid KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
71
+ )
72
+ return parsed
73
+ return DEFAULT_CACHE_TTL_HOURS
74
+
75
+
76
+ @contextmanager
77
+ def file_lock(lock_path: Path) -> Iterator[None]:
78
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
79
+ try:
80
+ import fcntl
81
+ except ImportError:
82
+ yield
83
+ return
84
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
85
+ with open(lock_path, "a+b") as lock_file:
86
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
87
+ try:
88
+ yield
89
+ finally:
90
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
91
+
92
+
93
+ def atomic_write_json(dest: Path, payload: Any) -> None:
94
+ dest.parent.mkdir(parents=True, exist_ok=True)
95
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
96
+ try:
97
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
98
+ os.replace(tmp, dest)
99
+ except Exception:
100
+ tmp.unlink(missing_ok=True)
101
+ raise
102
+
103
+
104
+ def cache_key(kind: str, payload: dict) -> str:
105
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
106
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
107
+
108
+
109
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
110
+ if not path.is_file():
111
+ return None
112
+ try:
113
+ entry = json.loads(path.read_text(encoding="utf-8"))
114
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
115
+ return None
116
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
117
+ return None
118
+ fetched = entry.get("fetched_at")
119
+ if not isinstance(fetched, (int, float)):
120
+ return None
121
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
122
+ return None
123
+ result = entry.get("result")
124
+ return result if isinstance(result, dict) else None
125
+
126
+
127
+ def cached_call(
128
+ kind: str,
129
+ payload: dict,
130
+ fetch: Callable[[], dict],
131
+ *,
132
+ refresh: bool,
133
+ ttl_hours: float,
134
+ cacheable: Callable[[dict], bool] = lambda _r: True,
135
+ ) -> tuple[dict, bool]:
136
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
137
+ key = cache_key(kind, payload)
138
+ root = cache_dir()
139
+ path = root / f"{key}.json"
140
+ if not refresh:
141
+ hit = read_cache(path, ttl_hours)
142
+ if hit is not None:
143
+ return hit, True
144
+ with file_lock(root / f"{key}.lock"):
145
+ if not refresh:
146
+ hit = read_cache(path, ttl_hours)
147
+ if hit is not None:
148
+ return hit, True
149
+ result = fetch()
150
+ if cacheable(result):
151
+ atomic_write_json(
152
+ path,
153
+ {
154
+ "schema": CACHE_SCHEMA,
155
+ "fetched_at": time.time(),
156
+ "kind": kind,
157
+ "query": payload,
158
+ "result": result,
159
+ },
160
+ )
161
+ return result, False
162
+
163
+
164
+ def cache_options(func: Callable) -> Callable:
165
+ func = click.option(
166
+ "--cache-ttl-hours",
167
+ type=float,
168
+ default=None,
169
+ help="Cache TTL in hours (default 168, env KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
170
+ )(func)
171
+ func = click.option(
172
+ "--refresh",
173
+ is_flag=True,
174
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
175
+ )(func)
176
+ return func
177
+
40
178
  BASE = "https://s1.sos.mo.gov"
41
179
  DEATH_PAGE = BASE + "/records/Archives/ArchivesMvc/DeathCertificates/"
42
180
  DEATH_POST = BASE + "/Records/Archives/ArchivesMvc/"
@@ -152,15 +290,22 @@ def _form_token(html):
152
290
 
153
291
  def _post_search(client, page_url, post_url, data):
154
292
  """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
293
+ try:
294
+ page = client.get(page_url)
295
+ page.raise_for_status()
296
+ token = _form_token(page.text)
297
+ if token:
298
+ data = dict(data)
299
+ data["__ncforminfo"] = token
300
+ resp = client.post(post_url, data=data)
301
+ resp.raise_for_status()
302
+ return resp.text
303
+ except httpx.HTTPStatusError as exc:
304
+ raise click.ClickException(
305
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
306
+ ) from exc
307
+ except httpx.HTTPError as exc:
308
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
164
309
 
165
310
 
166
311
  def _parse_death_name(text):
@@ -245,19 +390,26 @@ def _pre1910_rows(html, kind):
245
390
 
246
391
  def _fetch_pages(client, first_html, results_url, parse, limit):
247
392
  """Follow the session pager (50/page) until limit or total reached."""
248
- total = _total_results(first_html)
393
+ raw_total = _total_results(first_html)
249
394
  records = parse(first_html)
250
- if total is None:
251
- total = len(records)
395
+ total = raw_total if raw_total is not None else len(records)
252
396
  page = 2
253
397
  while len(records) < min(limit, total):
254
- resp = client.get(
255
- results_url, params={"PageNumber": page, "recordsPerPage": 50}
256
- )
257
- resp.raise_for_status()
398
+ try:
399
+ resp = client.get(
400
+ results_url, params={"PageNumber": page, "recordsPerPage": 50}
401
+ )
402
+ resp.raise_for_status()
403
+ except httpx.HTTPStatusError as exc:
404
+ raise click.ClickException(
405
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
406
+ ) from exc
407
+ except httpx.HTTPError as exc:
408
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
258
409
  records.extend(parse(resp.text))
259
410
  page += 1
260
- return total, records[:limit]
411
+ verified = bool(records) or raw_total is not None
412
+ return total, records[:limit], verified
261
413
 
262
414
 
263
415
  def _detail_fields(html):
@@ -289,14 +441,55 @@ def _detail_fields(html):
289
441
  def _download_pdf(client, url, dest, overwrite):
290
442
  if dest.exists() and not overwrite:
291
443
  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)
444
+ try:
445
+ with client.stream("GET", url) as resp:
446
+ resp.raise_for_status()
447
+ with dest.open("wb") as fh:
448
+ for chunk in resp.iter_bytes():
449
+ fh.write(chunk)
450
+ except httpx.HTTPStatusError as exc:
451
+ raise click.ClickException(
452
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
453
+ ) from exc
454
+ except httpx.HTTPError as exc:
455
+ raise click.ClickException(f"Missouri Archives download failed: {exc}") from exc
297
456
  return dest, False
298
457
 
299
458
 
459
+ def _search_death(data: dict, limit: int) -> dict:
460
+ with _client() as client:
461
+ first_html = _post_search(client, DEATH_PAGE, DEATH_POST, data)
462
+ total, records, verified = _fetch_pages(
463
+ client, first_html, DEATH_RESULTS, _death_rows, limit
464
+ )
465
+ return {"total": total, "results": records, "verified": verified}
466
+
467
+
468
+ def _search_pre1910(kind: str, data: dict, limit: int) -> dict:
469
+ parse = lambda html: _pre1910_rows(html, kind)
470
+ with _client() as client:
471
+ first_html = _post_search(client, PRE1910_PAGE, PRE1910_POST, data)
472
+ total, records, verified = _fetch_pages(
473
+ client, first_html, PRE1910_RESULTS, parse, limit
474
+ )
475
+ return {"total": total, "results": records, "verified": verified}
476
+
477
+
478
+ def _fetch_detail(clean_id: str) -> dict:
479
+ url = f"{PRE1910_DETAIL}?id={clean_id}"
480
+ try:
481
+ with _client() as client:
482
+ resp = client.get(url)
483
+ resp.raise_for_status()
484
+ except httpx.HTTPStatusError as exc:
485
+ raise click.ClickException(
486
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
487
+ ) from exc
488
+ except httpx.HTTPError as exc:
489
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
490
+ return {"id": clean_id, "url": url, "fields": _detail_fields(resp.text)}
491
+
492
+
300
493
  @click.group(context_settings={"help_option_names": ["-h", "--help"]})
301
494
  def cli():
302
495
  """Search Missouri State Archives vital records (no key, no login)."""
@@ -334,10 +527,11 @@ def cli():
334
527
  default=None,
335
528
  help="Download each result's certificate PDF into DIR.",
336
529
  )
530
+ @cache_options
337
531
  def cmd_death(
338
532
  last, first, middle, role, match, county,
339
533
  begin_year, end_year, begin_month, end_month,
340
- limit, as_json, download_dir,
534
+ limit, as_json, download_dir, refresh, cache_ttl_hours,
341
535
  ):
342
536
  """Search Missouri Death Certificates, 1910-1975 (with images)."""
343
537
  if not 1910 <= begin_year <= end_year <= 1975:
@@ -363,28 +557,42 @@ def cmd_death(
363
557
  "CountyName": county or ALL_COUNTIES,
364
558
  "Search": "Search",
365
559
  }
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
- )
560
+ cache_payload = {
561
+ "last": last, "first": first, "middle": middle, "role": role,
562
+ "match": match, "county": county, "begin_year": begin_year,
563
+ "end_year": end_year, "begin_month": begin_month,
564
+ "end_month": end_month, "limit": limit,
565
+ }
566
+ ttl = resolve_ttl_hours(cache_ttl_hours)
567
+ result, hit = cached_call(
568
+ "death",
569
+ cache_payload,
570
+ lambda: _search_death(data, limit),
571
+ refresh=refresh,
572
+ ttl_hours=ttl,
573
+ cacheable=lambda r: bool(r.get("verified")),
574
+ )
575
+ total = result["total"]
576
+ records = result["results"]
577
+ if download_dir:
578
+ download_dir.mkdir(parents=True, exist_ok=True)
579
+ to_download = [rec for rec in records if rec.get("image")]
580
+ if to_download:
581
+ with _client() as client:
582
+ for rec in to_download:
583
+ fname = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(rec["image"]).name)
584
+ dest, skipped = _download_pdf(
585
+ client, rec["image"], download_dir / fname, overwrite=False
586
+ )
587
+ click.echo(
588
+ f"{'Exists (skip)' if skipped else 'Downloaded'}: {dest} "
589
+ f"({dest.stat().st_size:,} bytes)"
590
+ )
384
591
  if as_json:
385
- click.echo(json.dumps({"total": total, "results": records}, indent=2))
592
+ click.echo(json.dumps({"total": total, "results": records, "cache_hit": hit}, indent=2))
386
593
  return
387
- click.echo(f"Total: {total} | showing {len(records)}")
594
+ marker = " [cache]" if hit else ""
595
+ click.echo(f"Total: {total} | showing {len(records)}{marker}")
388
596
  for rec in records:
389
597
  parts = [rec["name"]]
390
598
  if rec.get("age"):
@@ -409,7 +617,8 @@ def cmd_death(
409
617
  @click.option("--county", default="", help="County as spelled on the site; default all counties.")
410
618
  @click.option("--limit", type=int, default=50, show_default=True, help="Max records (50 per page).")
411
619
  @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
412
- def cmd_pre1910(kind, name, county, limit, as_json):
620
+ @cache_options
621
+ def cmd_pre1910(kind, name, county, limit, as_json, refresh, cache_ttl_hours):
413
622
  """Search the pre-1910 Birth and Death Records Database (abstracts)."""
414
623
  if limit < 1:
415
624
  raise click.BadParameter("--limit must be at least 1.")
@@ -425,16 +634,23 @@ def cmd_pre1910(kind, name, county, limit, as_json):
425
634
  "BirthNameSearch": name,
426
635
  "BirthSubmit": "Search",
427
636
  }
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
- )
637
+ cache_payload = {"kind": kind, "name": name, "county": county, "limit": limit}
638
+ ttl = resolve_ttl_hours(cache_ttl_hours)
639
+ result, hit = cached_call(
640
+ "pre1910",
641
+ cache_payload,
642
+ lambda: _search_pre1910(kind, data, limit),
643
+ refresh=refresh,
644
+ ttl_hours=ttl,
645
+ cacheable=lambda r: bool(r.get("verified")),
646
+ )
647
+ total = result["total"]
648
+ records = result["results"]
434
649
  if as_json:
435
- click.echo(json.dumps({"total": total, "results": records}, indent=2))
650
+ click.echo(json.dumps({"total": total, "results": records, "cache_hit": hit}, indent=2))
436
651
  return
437
- click.echo(f"Total: {total} | showing {len(records)}")
652
+ marker = " [cache]" if hit else ""
653
+ click.echo(f"Total: {total} | showing {len(records)}{marker}")
438
654
  for rec in records:
439
655
  if kind == "death":
440
656
  parts = [
@@ -462,23 +678,30 @@ def cmd_pre1910(kind, name, county, limit, as_json):
462
678
  @cli.command("detail")
463
679
  @click.argument("ids", nargs=-1, required=True)
464
680
  @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
465
- def cmd_detail(ids, as_json):
681
+ @cache_options
682
+ def cmd_detail(ids, as_json, refresh, cache_ttl_hours):
466
683
  """Fetch full abstracts for pre-1910 record IDs (from `pre1910`)."""
684
+ ttl = resolve_ttl_hours(cache_ttl_hours)
467
685
  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)})
686
+ for rid in ids:
687
+ clean = re.sub(r"\D+", "", rid)
688
+ rec, hit = cached_call(
689
+ "detail",
690
+ {"id": clean},
691
+ lambda cid=clean: _fetch_detail(cid),
692
+ refresh=refresh,
693
+ ttl_hours=ttl,
694
+ cacheable=lambda r: bool(r.get("fields")),
695
+ )
696
+ records.append({**rec, "cache_hit": hit})
475
697
  if as_json:
476
698
  click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
477
699
  return
478
700
  for idx, rec in enumerate(records):
479
701
  if idx > 0:
480
702
  click.echo("")
481
- click.echo(f"Detail {rec['id']}: {rec['url']}")
703
+ marker = " [cache]" if rec.get("cache_hit") else ""
704
+ click.echo(f"Detail {rec['id']}: {rec['url']}{marker}")
482
705
  for key, val in rec["fields"].items():
483
706
  click.echo(f" {key}: {val}")
484
707
 
@@ -15,6 +15,16 @@ This skill includes a standalone executable Python CLI at `skills/nara-catalog-s
15
15
 
16
16
  Path: `skills/nara-catalog-search/scripts/nara`
17
17
 
18
+ ### Persistent local disk cache
19
+
20
+ `search`, `get`, and `download` cache responses atomically under `~/.cache/kinloom-nara/` (overrideable via `KINLOOM_NARA_CACHE_DIR`) using advisory file locks (`fcntl.flock` on POSIX, safe fallback elsewhere) so concurrent research threads never duplicate downloads and repeat calls make zero HTTP requests. Pass `--refresh` on `search`, `get`, or `download` to bypass the cache and fetch fresh data.
21
+
22
+ Cache layout:
23
+
24
+ - `records/<naid>.json`: full record metadata and digital object inventory shared by `get` and `download` (upgraded automatically if `--text` is requested later).
25
+ - `objects/<naid>/<page>_<safe_filename>`: individual downloaded page scans, so overlapping page slices (for example `--pages 315-350` followed by `--pages 340-360` or another biographer working the same census roll) reuse already-fetched pages straight from disk.
26
+ - `_queries/<sha256>.json`: cached `search` query payloads keyed by canonical query parameters with a 168-hour (7-day) default TTL (`--cache-ttl-hours` or `KINLOOM_NARA_QUERY_TTL_HOURS`).
27
+
18
28
  ### Search records (single or batched in one browser session)
19
29
 
20
30
  ```bash
@@ -64,6 +74,8 @@ skills/nara-catalog-search/scripts/nara url '"Clara Barton"' --level item --api
64
74
 
65
75
  - `NARA_API_KEY`: optional NARA Catalog v2 API key for direct HTTP queries.
66
76
  - `NARA_BROWSER`: optional path to a Chromium or Chrome binary (defaults to `chromium`, `chromium-browser`, `google-chrome`, or Playwright's bundled browser).
77
+ - `KINLOOM_NARA_CACHE_DIR`: optional override for the local disk cache directory (default `~/.cache/kinloom-nara`).
78
+ - `KINLOOM_NARA_QUERY_TTL_HOURS`: optional override for the `search` query cache TTL in hours (default `168`).
67
79
 
68
80
  ## Website search & query string rules (verified live 2026-11-23)
69
81