@kinloom/cli 0.2.0 → 0.3.1

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 +272 -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
@@ -28,14 +28,153 @@ ukcc.uky.edu/vitalrec URL did not resolve live 2026-11-24).
28
28
 
29
29
  from __future__ import annotations
30
30
 
31
+ import hashlib
31
32
  import html as htmlmod
32
33
  import json
34
+ import math
35
+ import os
33
36
  import re
37
+ import time
38
+ from contextlib import contextmanager
39
+ from pathlib import Path
40
+ from typing import Any, Callable, Iterator
34
41
  from urllib.parse import quote
35
42
 
36
43
  import click
37
44
  import httpx
38
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_KY_ARCHIVES_CACHE_DIR")
52
+ if override:
53
+ return Path(override).expanduser()
54
+ return Path.home() / ".cache" / "kinloom-ky-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_KY_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_KY_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_KY_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_KY_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
+
39
178
  CDM_BASE = "https://www.kyhistory.com"
40
179
  CDM_API = CDM_BASE + "/digital/api"
41
180
  LAND_URL = "https://web.sos.ky.gov/land/ccorders.aspx"
@@ -83,6 +222,35 @@ def _clean(text: str) -> str:
83
222
  return re.sub(r"\s+", " ", text).strip()
84
223
 
85
224
 
225
+ def _get_json(client: httpx.Client, url: str) -> dict[str, Any]:
226
+ resp = _get(client, url)
227
+ try:
228
+ data = resp.json()
229
+ except ValueError as exc:
230
+ raise click.ClickException(f"Invalid JSON from {url}: {exc}") from exc
231
+ if not isinstance(data, dict):
232
+ raise click.ClickException(f"Unexpected JSON response from {url}")
233
+ return data
234
+
235
+
236
+ def _fetch_cdm(query: str, alias: str, field: str, limit: int) -> dict[str, Any]:
237
+ url = (
238
+ f"{CDM_API}/search/collection/{alias}/searchterm/{quote(query)}/"
239
+ f"field/{field}/maxRecords/{limit}"
240
+ )
241
+ with _client() as client:
242
+ data = _get_json(client, url)
243
+ total = data.get("totalResults", 0)
244
+ items = data.get("items", [])
245
+ trimmed = [
246
+ {k: it.get(k) for k in ("collectionAlias", "itemId", "title", "filetype", "itemLink")}
247
+ | {"fields": {f["field"]: f["value"] for f in it.get("metadataFields", [])}}
248
+ for it in items
249
+ ]
250
+ verified = isinstance(data.get("items"), list) and isinstance(data.get("totalResults"), int)
251
+ return {"totalResults": total, "items": trimmed, "verified": verified}
252
+
253
+
86
254
  # ---------------------------------------------------------------- CONTENTdm
87
255
  @click.command("cdm")
88
256
  @click.argument("query")
@@ -92,65 +260,114 @@ def _clean(text: str) -> str:
92
260
  help="Search field: all, title, descri, date, subjec, publis, source (default: all).")
93
261
  @click.option("--limit", default=10, type=int, show_default=True)
94
262
  @click.option("--json", "as_json", is_flag=True, help="Print raw trimmed JSON.")
95
- def cdm_cmd(query: str, alias: str, field: str, limit: int, as_json: bool) -> None:
263
+ @cache_options
264
+ def cdm_cmd(
265
+ query: str,
266
+ alias: str,
267
+ field: str,
268
+ limit: int,
269
+ as_json: bool,
270
+ refresh: bool,
271
+ cache_ttl_hours: float | None,
272
+ ) -> None:
96
273
  """Search KHS Digital Collections (CONTENTdm API)."""
97
- url = (
98
- f"{CDM_API}/search/collection/{alias}/searchterm/{quote(query)}/"
99
- f"field/{field}/maxRecords/{limit}"
274
+ ttl = resolve_ttl_hours(cache_ttl_hours)
275
+ data, hit = cached_call(
276
+ "cdm",
277
+ {"query": query, "alias": alias, "field": field, "limit": limit},
278
+ lambda: _fetch_cdm(query, alias, field, limit),
279
+ refresh=refresh,
280
+ ttl_hours=ttl,
281
+ cacheable=lambda r: bool(r.get("verified")),
100
282
  )
101
- with _client() as client:
102
- data = _get(client, url).json()
103
283
  total = data.get("totalResults", 0)
104
284
  items = data.get("items", [])
105
285
  if as_json:
106
- click.echo(json.dumps(
107
- {"totalResults": total,
108
- "items": [{k: it.get(k) for k in
109
- ("collectionAlias", "itemId", "title", "filetype", "itemLink")
110
- } | {"fields": {f["field"]: f["value"]
111
- for f in it.get("metadataFields", [])}}
112
- for it in items]},
113
- indent=2))
286
+ click.echo(json.dumps({"totalResults": total, "items": items, "cache_hit": hit}, indent=2))
114
287
  return
115
- click.echo(f"{total} result(s) for {query!r} in KHS Digital Collections")
288
+ marker = " [cache]" if hit else ""
289
+ click.echo(f"{total} result(s) for {query!r} in KHS Digital Collections{marker}")
116
290
  for it in items:
117
- fields = {f["field"]: f["value"] for f in it.get("metadataFields", [])}
291
+ fields = it.get("fields") or {}
118
292
  date = fields.get("date", "")
119
293
  click.echo(f"- [{it.get('collectionAlias')}:{it.get('itemId')}] "
120
294
  f"{it.get('title')}" + (f" ({date})" if date else ""))
121
295
  click.echo(f" {CDM_BASE}/digital{it.get('itemLink', '')}")
122
296
 
123
297
 
298
+ def _fetch_cdm_item(alias: str, item_id: str) -> dict[str, Any]:
299
+ url = f"{CDM_API}/singleitem/collection/{alias}/id/{item_id}"
300
+ with _client() as client:
301
+ return _get_json(client, url)
302
+
303
+
124
304
  @click.command("cdm-item")
125
305
  @click.argument("alias")
126
306
  @click.argument("item_id")
127
307
  @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
128
- def cdm_item_cmd(alias: str, item_id: str, as_json: bool) -> None:
308
+ @cache_options
309
+ def cdm_item_cmd(
310
+ alias: str,
311
+ item_id: str,
312
+ as_json: bool,
313
+ refresh: bool,
314
+ cache_ttl_hours: float | None,
315
+ ) -> None:
129
316
  """Show full metadata for one CONTENTdm item: ALIAS ITEM_ID."""
130
- url = f"{CDM_API}/singleitem/collection/{alias}/id/{item_id}"
131
- with _client() as client:
132
- data = _get(client, url).json()
317
+ ttl = resolve_ttl_hours(cache_ttl_hours)
318
+ data, hit = cached_call(
319
+ "cdm-item",
320
+ {"alias": alias, "item_id": item_id},
321
+ lambda: _fetch_cdm_item(alias, item_id),
322
+ refresh=refresh,
323
+ ttl_hours=ttl,
324
+ cacheable=lambda r: bool(r.get("fields") or r.get("title") or r.get("contentType")),
325
+ )
133
326
  if as_json:
134
- click.echo(json.dumps(data, indent=2))
327
+ click.echo(json.dumps({**data, "cache_hit": hit}, indent=2))
135
328
  return
136
- click.echo(f"{CDM_BASE}/digital/singleitem/collection/{alias}/id/{item_id}")
329
+ marker = " [cache]" if hit else ""
330
+ click.echo(f"{CDM_BASE}/digital/singleitem/collection/{alias}/id/{item_id}{marker}")
137
331
  for f in data.get("fields", []):
138
332
  click.echo(f"{f.get('label', f.get('key'))}: {f.get('value')}")
139
333
  if data.get("contentType"):
140
334
  click.echo(f"Content-Type: {data['contentType']}")
141
335
 
142
336
 
337
+ def _fetch_collections() -> dict[str, Any]:
338
+ with _client() as client:
339
+ return _get_json(client, f"{CDM_API}/collections")
340
+
341
+
143
342
  @click.command("collections")
144
343
  @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
145
- def collections_cmd(as_json: bool) -> None:
344
+ @cache_options
345
+ def collections_cmd(as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
146
346
  """List the KHS Digital Collections (CONTENTdm aliases)."""
147
- with _client() as client:
148
- data = _get(client, f"{CDM_API}/collections").json()
347
+ ttl = resolve_ttl_hours(cache_ttl_hours)
348
+ data, hit = cached_call(
349
+ "collections",
350
+ {},
351
+ _fetch_collections,
352
+ refresh=refresh,
353
+ ttl_hours=ttl,
354
+ cacheable=lambda r: bool(r.get("cards")),
355
+ )
149
356
  cards = data.get("cards", [])
150
357
  if as_json:
151
- click.echo(json.dumps(cards, indent=2))
358
+ click.echo(
359
+ json.dumps(
360
+ {
361
+ "totalCollections": data.get("totalCollections", len(cards)),
362
+ "cards": cards,
363
+ "cache_hit": hit,
364
+ },
365
+ indent=2,
366
+ )
367
+ )
152
368
  return
153
- click.echo(f"{data.get('totalCollections', len(cards))} collections")
369
+ marker = " [cache]" if hit else ""
370
+ click.echo(f"{data.get('totalCollections', len(cards))} collections{marker}")
154
371
  for c in cards:
155
372
  click.echo(f"- {c.get('alias')}: {c.get('title')}")
156
373
 
@@ -184,7 +401,7 @@ def _land_post(client: httpx.Client, data: dict[str, str]) -> str:
184
401
  return resp.text
185
402
 
186
403
 
187
- def _parse_land_results(page_html: str) -> tuple[int, list[dict[str, str]]]:
404
+ def _parse_land_results(page_html: str) -> tuple[int, list[dict[str, str]], bool]:
188
405
  text = _clean(page_html)
189
406
  m = re.search(r"(\d+) Results found", text)
190
407
  total = int(m.group(1)) if m else 0
@@ -205,14 +422,16 @@ def _parse_land_results(page_html: str) -> tuple[int, list[dict[str, str]]]:
205
422
  "watercourse", "survey_name", "survey_date", "grant_date",
206
423
  "grant_note")
207
424
  results.append(dict(zip(keys, (g.strip() for g in fm.groups()))))
208
- return total, results
425
+ verified = bool(results) or (m is not None)
426
+ return total, results, verified
209
427
 
210
428
 
211
- def _print_land(total: int, results: list[dict[str, str]], as_json: bool) -> None:
429
+ def _print_land(total: int, results: list[dict[str, str]], as_json: bool, cache_hit: bool = False) -> None:
212
430
  if as_json:
213
- click.echo(json.dumps({"totalResults": total, "results": results}, indent=2))
431
+ click.echo(json.dumps({"totalResults": total, "results": results, "cache_hit": cache_hit}, indent=2))
214
432
  return
215
- click.echo(f"{total} patent(s) found")
433
+ marker = " [cache]" if cache_hit else ""
434
+ click.echo(f"{total} patent(s) found{marker}")
216
435
  for r in results:
217
436
  click.echo(f"- Patent #{r['patent']}: {r['grantee']} "
218
437
  f"({r['county']} Co., grant {r['grant_date']}, "
@@ -222,21 +441,9 @@ def _print_land(total: int, results: list[dict[str, str]], as_json: bool) -> Non
222
441
  f"survey name: {r['survey_name']}")
223
442
 
224
443
 
225
- @click.command("land")
226
- @click.argument("term")
227
- @click.option("--by", "by", default="grantee", type=click.Choice(sorted(LAND_BY)),
228
- show_default=True, help="Advanced-search field.")
229
- @click.option("--limit", default=10, type=click.Choice(["10", "25", "50", "100"]),
230
- show_default=True, help="Results per page.")
231
- @click.option("--json", "as_json", is_flag=True, help="Print JSON.")
232
- def land_cmd(term: str, by: str, limit: str, as_json: bool) -> None:
233
- """Advanced search of County Court Orders patents (1835-2000).
234
-
235
- Example: ky-archives land Lincoln --by grantee
236
- """
444
+ def _fetch_land(term: str, by: str, limit: str) -> dict[str, Any]:
237
445
  with _client() as client:
238
446
  page = _get(client, LAND_URL).text
239
- # Open the advanced-search panel (postback), then search from it.
240
447
  adv = _land_post(client, _asp_state(page) | {
241
448
  "__EVENTTARGET": "ctl00$ContentPlaceHolder1$LbAdvSearch",
242
449
  "__EVENTARGUMENT": ""})
@@ -249,20 +456,11 @@ def land_cmd(term: str, by: str, limit: str, as_json: bool) -> None:
249
456
  "ctl00$ContentPlaceHolder1$ddlSortBy": "",
250
457
  "ctl00$ContentPlaceHolder1$ddlSortDir": "ASC",
251
458
  "ctl00$ContentPlaceHolder1$BtnAdvSearch": "Search"})
252
- total, results = _parse_land_results(results_html)
253
- _print_land(total, results, as_json)
459
+ total, results, verified = _parse_land_results(results_html)
460
+ return {"totalResults": total, "results": results, "verified": verified}
254
461
 
255
462
 
256
- @click.command("land-patent")
257
- @click.argument("number")
258
- @click.option("--book", default=None, help="Grant book number (quick search).")
259
- @click.option("--page", default=None, help="Grant book page (quick search).")
260
- @click.option("--json", "as_json", is_flag=True, help="Print JSON.")
261
- def land_patent_cmd(number: str, book: str | None, page: str | None, as_json: bool) -> None:
262
- """Quick search of County Court Orders patents by patent number.
263
-
264
- Example: ky-archives land-patent <patent-number>
265
- """
463
+ def _fetch_land_patent(number: str, book: str | None, page: str | None) -> dict[str, Any]:
266
464
  with _client() as client:
267
465
  state = _asp_state(_get(client, LAND_URL).text)
268
466
  data = state | {
@@ -272,24 +470,73 @@ def land_patent_cmd(number: str, book: str | None, page: str | None, as_json: bo
272
470
  "ctl00$ContentPlaceHolder1$TxtSPage": page or "",
273
471
  "ctl00$ContentPlaceHolder1$BtnSearch": "Search"}
274
472
  results_html = _land_post(client, data)
275
- total, results = _parse_land_results(results_html)
276
- _print_land(total, results, as_json)
473
+ total, results, verified = _parse_land_results(results_html)
474
+ return {"totalResults": total, "results": results, "verified": verified}
277
475
 
278
476
 
279
- # ---------------------------------------------------------------- Preservica
280
- @click.command("preservica")
281
- @click.argument("query")
282
- @click.option("--limit", default=10, type=int, show_default=True)
477
+ @click.command("land")
478
+ @click.argument("term")
479
+ @click.option("--by", "by", default="grantee", type=click.Choice(sorted(LAND_BY)),
480
+ show_default=True, help="Advanced-search field.")
481
+ @click.option("--limit", default="10", type=click.Choice(["10", "25", "50", "100"]),
482
+ show_default=True, help="Results per page.")
283
483
  @click.option("--json", "as_json", is_flag=True, help="Print JSON.")
284
- def preservica_cmd(query: str, limit: int, as_json: bool) -> None:
285
- """Search the KDLA Preservica e-archives (WordPress search RSS feed).
484
+ @cache_options
485
+ def land_cmd(
486
+ term: str,
487
+ by: str,
488
+ limit: str,
489
+ as_json: bool,
490
+ refresh: bool,
491
+ cache_ttl_hours: float | None,
492
+ ) -> None:
493
+ """Advanced search of County Court Orders patents (1835-2000).
286
494
 
287
- Returns the matching record pages (title + URL). The site's search
288
- is full-text (titles, descriptions, creators, document contents),
289
- so open a hit to confirm why it matched. Opening a packet and
290
- viewing its scans needs the browser; there is no public Preservica
291
- search API on this host (verified 2026-11-24).
495
+ Example: ky-archives land Lincoln --by grantee
292
496
  """
497
+ ttl = resolve_ttl_hours(cache_ttl_hours)
498
+ data, hit = cached_call(
499
+ "land",
500
+ {"term": term, "by": by, "limit": limit},
501
+ lambda: _fetch_land(term, by, limit),
502
+ refresh=refresh,
503
+ ttl_hours=ttl,
504
+ cacheable=lambda r: bool(r.get("verified")),
505
+ )
506
+ _print_land(data["totalResults"], data["results"], as_json, cache_hit=hit)
507
+
508
+
509
+ @click.command("land-patent")
510
+ @click.argument("number")
511
+ @click.option("--book", default=None, help="Grant book number (quick search).")
512
+ @click.option("--page", default=None, help="Grant book page (quick search).")
513
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON.")
514
+ @cache_options
515
+ def land_patent_cmd(
516
+ number: str,
517
+ book: str | None,
518
+ page: str | None,
519
+ as_json: bool,
520
+ refresh: bool,
521
+ cache_ttl_hours: float | None,
522
+ ) -> None:
523
+ """Quick search of County Court Orders patents by patent number.
524
+
525
+ Example: ky-archives land-patent <patent-number>
526
+ """
527
+ ttl = resolve_ttl_hours(cache_ttl_hours)
528
+ data, hit = cached_call(
529
+ "land-patent",
530
+ {"number": number, "book": book or "", "page": page or ""},
531
+ lambda: _fetch_land_patent(number, book, page),
532
+ refresh=refresh,
533
+ ttl_hours=ttl,
534
+ cacheable=lambda r: bool(r.get("verified")),
535
+ )
536
+ _print_land(data["totalResults"], data["results"], as_json, cache_hit=hit)
537
+
538
+
539
+ def _fetch_preservica(query: str, limit: int) -> dict[str, Any]:
293
540
  url = f"{PRESERVICA_BASE}/search/{quote(query)}/feed/rss2/"
294
541
  with _client() as client:
295
542
  feed = _get(client, url).text
@@ -309,12 +556,53 @@ def preservica_cmd(query: str, limit: int, as_json: bool) -> None:
309
556
  results.append({"title": title, "url": link})
310
557
  if len(results) >= limit:
311
558
  break
559
+ is_rss = "<rss" in feed.lower() or "<channel>" in feed.lower()
560
+ return {
561
+ "search_url": f"{PRESERVICA_BASE}/?s={quote(query)}",
562
+ "feed_url": url,
563
+ "results": results,
564
+ "verified": bool(results) or is_rss,
565
+ }
566
+
567
+
568
+ # ---------------------------------------------------------------- Preservica
569
+ @click.command("preservica")
570
+ @click.argument("query")
571
+ @click.option("--limit", default=10, type=int, show_default=True)
572
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON.")
573
+ @cache_options
574
+ def preservica_cmd(
575
+ query: str,
576
+ limit: int,
577
+ as_json: bool,
578
+ refresh: bool,
579
+ cache_ttl_hours: float | None,
580
+ ) -> None:
581
+ """Search the KDLA Preservica e-archives (WordPress search RSS feed).
582
+
583
+ Returns the matching record pages (title + URL). The site's search
584
+ is full-text (titles, descriptions, creators, document contents),
585
+ so open a hit to confirm why it matched. Opening a packet and
586
+ viewing its scans needs the browser; there is no public Preservica
587
+ search API on this host (verified 2026-11-24).
588
+ """
589
+ ttl = resolve_ttl_hours(cache_ttl_hours)
590
+ data, hit = cached_call(
591
+ "preservica",
592
+ {"query": query, "limit": limit},
593
+ lambda: _fetch_preservica(query, limit),
594
+ refresh=refresh,
595
+ ttl_hours=ttl,
596
+ cacheable=lambda r: bool(r.get("verified")),
597
+ )
598
+ results = data["results"]
312
599
  if as_json:
313
600
  click.echo(json.dumps(
314
- {"search_url": f"{PRESERVICA_BASE}/?s={quote(query)}",
315
- "feed_url": url, "results": results}, indent=2))
601
+ {"search_url": data["search_url"],
602
+ "feed_url": data["feed_url"], "results": results, "cache_hit": hit}, indent=2))
316
603
  return
317
- click.echo(f"KDLA Preservica search: {PRESERVICA_BASE}/?s={quote(query)}")
604
+ marker = " [cache]" if hit else ""
605
+ click.echo(f"KDLA Preservica search: {data['search_url']}{marker}")
318
606
  if not results:
319
607
  click.echo("No results in the search feed.")
320
608
  return
@@ -102,9 +102,16 @@ Michigan residents can use the Library of Michigan's subscription databases remo
102
102
  5. For land and neighborhood context, pair surveyor maps and the map collection with county plat maps and atlases held in Lansing or digitized at the University of Michigan.
103
103
  6. Record every hit in `data/` with its Michiganology item URL; item URLs are stable (`michigan.access.preservica.com/uncategorized/SO_<uuid>` or `IO_<uuid>`).
104
104
 
105
- ## Environment variables
105
+ ## Disk cache and environment variables
106
106
 
107
- None. No key or account is needed for Michiganology search.
107
+ `search` and `get` cache successful responses on disk under `~/.cache/kinloom-michiganology/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP/curl errors and unparsed or blocked pages are never cached.
108
+
109
+ - `--refresh`: bypass cached reads and write the fresh response to disk.
110
+ - `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
111
+ - `KINLOOM_MICHIGANOLOGY_CACHE_DIR`: override the cache directory path.
112
+ - `KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS`: override the default TTL in hours.
113
+
114
+ No key or account is needed for Michiganology search.
108
115
 
109
116
  ## Verified-live note
110
117