@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
@@ -34,17 +34,27 @@ Browser-only (use the ``url`` command):
34
34
 
35
35
  from __future__ import annotations
36
36
 
37
+ import hashlib
37
38
  import html as htmlmod
38
39
  import json
40
+ import math
41
+ import os
39
42
  import re
40
43
  import subprocess
44
+ import time
41
45
  import xml.etree.ElementTree as ET
46
+ from contextlib import contextmanager
42
47
  from datetime import date
48
+ from pathlib import Path
49
+ from typing import Any, Callable, Iterator
43
50
  from urllib.parse import quote, urlencode
44
51
 
45
52
  import click
46
53
  import httpx
47
54
 
55
+ DEFAULT_CACHE_TTL_HOURS = 168.0
56
+ CACHE_SCHEMA = 1
57
+
48
58
  PORTAL_BASE = "https://texashistory.unt.edu"
49
59
  PORTAL_OPENSEARCH = PORTAL_BASE + "/search/opensearch/"
50
60
  PORTAL_OAI = PORTAL_BASE + "/oai/"
@@ -60,6 +70,137 @@ TIMEOUT = 60.0
60
70
  OAI_NS = {"oai": "http://www.openarchives.org/OAI/2.0/", "dc": "http://purl.org/dc/elements/1.1/"}
61
71
 
62
72
 
73
+ def cache_dir() -> Path:
74
+ override = os.environ.get("KINLOOM_TEXAS_ARCHIVES_CACHE_DIR")
75
+ if override:
76
+ return Path(override).expanduser()
77
+ return Path.home() / ".cache" / "kinloom-texas-archives"
78
+
79
+
80
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
81
+ if cli_ttl is not None:
82
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
83
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
84
+ return float(cli_ttl)
85
+ raw = os.environ.get("KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS")
86
+ if raw is not None and raw.strip():
87
+ try:
88
+ parsed = float(raw.strip())
89
+ except ValueError as exc:
90
+ raise click.BadParameter(
91
+ f"Invalid KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}."
92
+ ) from exc
93
+ if not math.isfinite(parsed) or parsed < 0:
94
+ raise click.BadParameter(
95
+ f"Invalid KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
96
+ )
97
+ return parsed
98
+ return DEFAULT_CACHE_TTL_HOURS
99
+
100
+
101
+ @contextmanager
102
+ def file_lock(lock_path: Path) -> Iterator[None]:
103
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
104
+ try:
105
+ import fcntl
106
+ except ImportError:
107
+ yield
108
+ return
109
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
110
+ with open(lock_path, "a+b") as lock_file:
111
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
112
+ try:
113
+ yield
114
+ finally:
115
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
116
+
117
+
118
+ def atomic_write_json(dest: Path, payload: Any) -> None:
119
+ dest.parent.mkdir(parents=True, exist_ok=True)
120
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
121
+ try:
122
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
123
+ os.replace(tmp, dest)
124
+ except Exception:
125
+ tmp.unlink(missing_ok=True)
126
+ raise
127
+
128
+
129
+ def cache_key(kind: str, payload: dict) -> str:
130
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
131
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
132
+
133
+
134
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
135
+ if not path.is_file():
136
+ return None
137
+ try:
138
+ entry = json.loads(path.read_text(encoding="utf-8"))
139
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
140
+ return None
141
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
142
+ return None
143
+ fetched = entry.get("fetched_at")
144
+ if not isinstance(fetched, (int, float)):
145
+ return None
146
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
147
+ return None
148
+ result = entry.get("result")
149
+ return result if isinstance(result, dict) else None
150
+
151
+
152
+ def cached_call(
153
+ kind: str,
154
+ payload: dict,
155
+ fetch: Callable[[], dict],
156
+ *,
157
+ refresh: bool,
158
+ ttl_hours: float,
159
+ cacheable: Callable[[dict], bool] = lambda _r: True,
160
+ ) -> tuple[dict, bool]:
161
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
162
+ key = cache_key(kind, payload)
163
+ root = cache_dir()
164
+ path = root / f"{key}.json"
165
+ if not refresh:
166
+ hit = read_cache(path, ttl_hours)
167
+ if hit is not None:
168
+ return hit, True
169
+ with file_lock(root / f"{key}.lock"):
170
+ if not refresh:
171
+ hit = read_cache(path, ttl_hours)
172
+ if hit is not None:
173
+ return hit, True
174
+ result = fetch()
175
+ if cacheable(result):
176
+ atomic_write_json(
177
+ path,
178
+ {
179
+ "schema": CACHE_SCHEMA,
180
+ "fetched_at": time.time(),
181
+ "kind": kind,
182
+ "query": payload,
183
+ "result": result,
184
+ },
185
+ )
186
+ return result, False
187
+
188
+
189
+ def cache_options(func: Callable) -> Callable:
190
+ func = click.option(
191
+ "--cache-ttl-hours",
192
+ type=float,
193
+ default=None,
194
+ help="Cache TTL in hours (default 168, env KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
195
+ )(func)
196
+ func = click.option(
197
+ "--refresh",
198
+ is_flag=True,
199
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
200
+ )(func)
201
+ return func
202
+
203
+
63
204
  def _client() -> httpx.Client:
64
205
  return httpx.Client(headers={"User-Agent": UA}, timeout=TIMEOUT, follow_redirects=True)
65
206
 
@@ -155,15 +296,25 @@ def _opensearch_entry(raw: dict) -> dict:
155
296
 
156
297
  def _fetch_opensearch_page(client: httpx.Client, query: str, page: int) -> dict:
157
298
  params = {"q": query, "format": "json", "pw": str(page)}
158
- resp = client.get(PORTAL_OPENSEARCH, params=params)
299
+ try:
300
+ resp = client.get(PORTAL_OPENSEARCH, params=params)
301
+ except httpx.HTTPError as exc:
302
+ raise click.ClickException(f"OpenSearch request failed: {exc}") from exc
159
303
  if resp.status_code != 200:
160
304
  raise click.ClickException(f"OpenSearch returned HTTP {resp.status_code}")
161
- data = resp.json()
305
+ try:
306
+ data = resp.json()
307
+ except ValueError as exc:
308
+ raise click.ClickException(f"OpenSearch returned non-JSON: {exc}") from exc
309
+ if not isinstance(data, dict):
310
+ raise click.ClickException("OpenSearch returned unexpected JSON shape")
162
311
  feed = data.get("feed") or {}
312
+ if not isinstance(feed, dict):
313
+ raise click.ClickException("OpenSearch returned malformed feed")
163
314
  total_s = feed.get("opensearch:totalResults", "0")
164
315
  try:
165
316
  total = int(total_s)
166
- except ValueError:
317
+ except (ValueError, TypeError):
167
318
  total = 0
168
319
  entries = [_opensearch_entry(e) for e in feed.get("entry") or []]
169
320
  return {"total": total, "page": page, "entries": entries}
@@ -177,7 +328,10 @@ def _build_portal_query(query: str, county: str | None) -> str:
177
328
 
178
329
 
179
330
  def _parse_oai_record(xml_text: str) -> dict:
180
- root = ET.fromstring(xml_text)
331
+ try:
332
+ root = ET.fromstring(xml_text)
333
+ except ET.ParseError as exc:
334
+ raise click.ClickException(f"OAI response was not valid XML: {exc}") from exc
181
335
  err = root.find("oai:error", OAI_NS)
182
336
  if err is not None:
183
337
  code = err.get("code", "error")
@@ -195,7 +349,6 @@ def _parse_oai_record(xml_text: str) -> dict:
195
349
  for s in header.findall("oai:setSpec", OAI_NS):
196
350
  if s.text:
197
351
  sets.append(s.text.strip())
198
- meta = rec.find(".//dc:title", OAI_NS)
199
352
  titles = [el.text.strip() for el in rec.findall(".//dc:title", OAI_NS) if el.text]
200
353
  creators = [el.text.strip() for el in rec.findall(".//dc:creator", OAI_NS) if el.text]
201
354
  subjects = [el.text.strip() for el in rec.findall(".//dc:subject", OAI_NS) if el.text]
@@ -223,7 +376,10 @@ def _parse_oai_record(xml_text: str) -> dict:
223
376
  def _fetch_portal_item(client: httpx.Client, ark_token: str) -> dict:
224
377
  ark = _normalize_ark(ark_token)
225
378
  params = {"verb": "GetRecord", "identifier": ark, "metadataPrefix": "oai_dc"}
226
- resp = client.get(PORTAL_OAI, params=params)
379
+ try:
380
+ resp = client.get(PORTAL_OAI, params=params)
381
+ except httpx.HTTPError as exc:
382
+ raise click.ClickException(f"OAI GetRecord request failed: {exc}") from exc
227
383
  if resp.status_code != 200:
228
384
  raise click.ClickException(f"OAI GetRecord returned HTTP {resp.status_code}")
229
385
  data = _parse_oai_record(resp.text)
@@ -255,7 +411,7 @@ def _curl_text(url: str) -> str:
255
411
  return proc.stdout
256
412
 
257
413
 
258
- def _fetch_tda_rss(query: str, limit: int) -> list[dict[str, str]]:
414
+ def _fetch_tda_rss(query: str, limit: int | None = None) -> list[dict[str, str]]:
259
415
  url = f"{TDA_BASE}/search/{quote(query)}/feed/rss2/"
260
416
  feed = _curl_text(url)
261
417
  results: list[dict[str, str]] = []
@@ -274,7 +430,7 @@ def _fetch_tda_rss(query: str, limit: int) -> list[dict[str, str]]:
274
430
  continue
275
431
  if title:
276
432
  results.append({"title": title, "url": link})
277
- if len(results) >= limit:
433
+ if limit is not None and len(results) >= limit:
278
434
  break
279
435
  return results
280
436
 
@@ -305,6 +461,7 @@ def portal() -> None:
305
461
  @click.option("--limit", default=10, show_default=True, type=int, help="Maximum hits to print after filters.")
306
462
  @click.option("--pages", default=3, show_default=True, type=int, help="OpenSearch pages to scan (100 hits each).")
307
463
  @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
464
+ @cache_options
308
465
  def cmd_portal_search(
309
466
  query: tuple[str, ...],
310
467
  county: str | None,
@@ -314,18 +471,38 @@ def cmd_portal_search(
314
471
  limit: int,
315
472
  pages: int,
316
473
  as_json: bool,
474
+ refresh: bool,
475
+ cache_ttl_hours: float | None,
317
476
  ) -> None:
318
477
  """Search the Portal via its public OpenSearch JSON API."""
319
478
  d_from = date.fromisoformat(date_from) if date_from else None
320
479
  d_to = date.fromisoformat(date_to) if date_to else None
480
+ ttl = resolve_ttl_hours(cache_ttl_hours)
321
481
  q = _build_portal_query(" ".join(query), county)
322
482
  matched: list[dict] = []
323
483
  total_reported = 0
324
- with _client() as client:
484
+ page_hits: list[bool] = []
485
+ client: httpx.Client | None = None
486
+ try:
325
487
  for page in range(1, pages + 1):
326
488
  if len(matched) >= limit:
327
489
  break
328
- batch = _fetch_opensearch_page(client, q, page)
490
+
491
+ def _fetch_page(p: int = page) -> dict:
492
+ nonlocal client
493
+ if client is None:
494
+ client = _client()
495
+ return _fetch_opensearch_page(client, q, p)
496
+
497
+ batch, hit = cached_call(
498
+ "portal_opensearch",
499
+ {"q": q, "page": page},
500
+ _fetch_page,
501
+ refresh=refresh,
502
+ ttl_hours=ttl,
503
+ cacheable=lambda r: bool(r.get("entries")) or int(r.get("total") or 0) > 0,
504
+ )
505
+ page_hits.append(hit)
329
506
  total_reported = batch["total"]
330
507
  if not batch["entries"] and page > 1:
331
508
  break
@@ -336,6 +513,10 @@ def cmd_portal_search(
336
513
  matched.append(entry)
337
514
  if len(matched) >= limit:
338
515
  break
516
+ finally:
517
+ if client is not None:
518
+ client.close()
519
+ all_cached = bool(page_hits) and all(page_hits)
339
520
  payload = {
340
521
  "query": q,
341
522
  "opensearch_total": total_reported,
@@ -343,11 +524,13 @@ def cmd_portal_search(
343
524
  "records": matched,
344
525
  "search_url": PORTAL_BASE + "/search/?" + urlencode({"q": q, "t": "fulltext"}),
345
526
  "note": "HTML search requires a browser (ALTCHA). Filters apply to OpenSearch fields only.",
527
+ "cache_hit": all_cached,
346
528
  }
347
529
  if as_json:
348
530
  click.echo(json.dumps(payload, indent=1))
349
531
  return
350
- click.echo(f"{total_reported} OpenSearch hit(s) for {q!r}; showing {len(matched)} after filters:")
532
+ marker = " [cache]" if all_cached else ""
533
+ click.echo(f"{total_reported} OpenSearch hit(s) for {q!r}; showing {len(matched)} after filters:{marker}")
351
534
  click.echo(payload["search_url"] + " (browser)")
352
535
  for rec in matched:
353
536
  _print_portal_hit(rec)
@@ -357,15 +540,35 @@ def cmd_portal_search(
357
540
  @portal.command("item")
358
541
  @click.argument("ark_id")
359
542
  @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
360
- def cmd_portal_item(ark_id: str, as_json: bool) -> None:
543
+ @cache_options
544
+ def cmd_portal_item(
545
+ ark_id: str,
546
+ as_json: bool,
547
+ refresh: bool,
548
+ cache_ttl_hours: float | None,
549
+ ) -> None:
361
550
  """Fetch Dublin Core metadata for one Portal item (OAI-PMH GetRecord)."""
362
- with _client() as client:
363
- data = _fetch_portal_item(client, ark_id)
551
+ ttl = resolve_ttl_hours(cache_ttl_hours)
552
+ ark = _normalize_ark(ark_id)
553
+
554
+ def _fetch() -> dict:
555
+ with _client() as client:
556
+ return _fetch_portal_item(client, ark)
557
+
558
+ data, hit = cached_call(
559
+ "portal_item",
560
+ {"ark": ark},
561
+ _fetch,
562
+ refresh=refresh,
563
+ ttl_hours=ttl,
564
+ cacheable=lambda r: bool(r.get("titles") or r.get("oai_identifier")),
565
+ )
364
566
  if as_json:
365
- click.echo(json.dumps(data, indent=1))
567
+ click.echo(json.dumps({**data, "cache_hit": hit}, indent=1))
366
568
  return
367
569
  title = (data.get("titles") or ["(no title)"])[0]
368
- click.echo(title)
570
+ marker = " [cache]" if hit else ""
571
+ click.echo(f"{title}{marker}")
369
572
  click.echo(f" {data['ark']}")
370
573
  if data.get("creators"):
371
574
  click.echo(" Creator(s): " + "; ".join(data["creators"][:6]))
@@ -383,19 +586,41 @@ def cmd_portal_item(ark_id: str, as_json: bool) -> None:
383
586
  @click.argument("query")
384
587
  @click.option("--limit", default=10, show_default=True, type=int)
385
588
  @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
386
- def cmd_tda(query: str, limit: int, as_json: bool) -> None:
589
+ @cache_options
590
+ def cmd_tda(
591
+ query: str,
592
+ limit: int,
593
+ as_json: bool,
594
+ refresh: bool,
595
+ cache_ttl_hours: float | None,
596
+ ) -> None:
387
597
  """Search the Texas Digital Archive (TSLAC Preservica RSS feed)."""
388
- results = _fetch_tda_rss(query, limit)
598
+ ttl = resolve_ttl_hours(cache_ttl_hours)
599
+
600
+ def _fetch() -> dict:
601
+ return {"results": _fetch_tda_rss(query, limit=None)}
602
+
603
+ data, hit = cached_call(
604
+ "tda_rss",
605
+ {"query": query.strip()},
606
+ _fetch,
607
+ refresh=refresh,
608
+ ttl_hours=ttl,
609
+ cacheable=lambda r: bool(r.get("results")),
610
+ )
611
+ results = (data.get("results") or [])[:limit]
389
612
  payload = {
390
613
  "search_url": f"{TDA_BASE}/?s={quote(query)}",
391
614
  "feed_url": f"{TDA_BASE}/search/{quote(query)}/feed/rss2/",
392
615
  "returned": len(results),
393
616
  "results": results,
617
+ "cache_hit": hit,
394
618
  }
395
619
  if as_json:
396
620
  click.echo(json.dumps(payload, indent=1))
397
621
  return
398
- click.echo(f"TDA search: {payload['search_url']}")
622
+ marker = " [cache]" if hit else ""
623
+ click.echo(f"TDA search: {payload['search_url']}{marker}")
399
624
  if not results:
400
625
  click.echo("No results in the RSS feed (feed returns at most ~25 items per query).")
401
626
  return
@@ -438,4 +663,4 @@ def cmd_url(query: str, portal: bool, tda: bool, glo: bool, rangers: bool, tslac
438
663
 
439
664
 
440
665
  if __name__ == "__main__":
441
- cli()
666
+ cli()
@@ -23,11 +23,11 @@ skills/uk-archives/scripts/uk-archives discovery search Lincoln --held-by Norfol
23
23
  skills/uk-archives/scripts/uk-archives discovery search Lincoln \
24
24
  --date-from 1550 --date-to 1660 --collection "PROB 11" --limit 20 --json
25
25
 
26
- # One record (verified detail endpoint uses /API/records/v1/details/<id>)
26
+ # One record (verified detail endpoint uses /API/records/v1/details/<id>; aliases: inspect, get)
27
27
  skills/uk-archives/scripts/uk-archives discovery detail <record-id> --json
28
28
  ```
29
29
 
30
- Search options: `--held-by` (free text appended to the query), `--date-from` / `--date-to` (YYYY or YYYY-MM-DD, mapped to `sps.dateFrom` / `sps.dateTo`), `--collection` (appended to the query and used to post-filter by catalogue reference), `--limit` (the API returns at most 15 rows per request; the CLI slices to your limit). Each hit prints id, reference, dates, title, places, and a Discovery web URL.
30
+ Search options: `--held-by` (free text appended to the query), `--date-from` / `--from-year` and `--date-to` / `--to-year` (YYYY or YYYY-MM-DD, mapped to `sps.dateFrom` / `sps.dateTo`), `--collection` (appended to the query and used to post-filter by catalogue reference), `--limit` (the API returns at most 15 rows per request; the CLI slices to your limit), `--query` / `-q` (alias for positional query). Each hit prints id, reference, dates, title, places, and a Discovery web URL.
31
31
 
32
32
  The detail route verified live is `https://discovery.nationalarchives.gov.uk/API/records/v1/details/<id>` (not `.../search/v1/records/v1/details/...`, which returns 404).
33
33
 
@@ -94,6 +94,15 @@ Priority order for English pre-emigration and parish research:
94
94
  - Nottinghamshire CalmView GET `https://nawcat.nottinghamshire.gov.uk/CalmView/`: connection timeout at 45s (browser-only note; no machine search).
95
95
  - CLI: `uv run --script skills/uk-archives/scripts/uk-archives --help`, `discovery search`, `discovery detail`, `freereg search`, and `url` all exited **0** on 2026-11-24.
96
96
 
97
+ ## Disk cache and environment variables
98
+
99
+ `discovery search`, `discovery detail` (`inspect`/`get`), and `freereg search` cache successful responses on disk under `~/.cache/kinloom-uk-archives/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors, malformed JSON, missing CSRF tokens, and empty responses are never cached.
100
+
101
+ - `--refresh`: bypass cached reads and write the fresh response to disk.
102
+ - `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
103
+ - `KINLOOM_UK_ARCHIVES_CACHE_DIR`: override the cache directory path.
104
+ - `KINLOOM_UK_ARCHIVES_CACHE_TTL_HOURS`: override the default TTL in hours.
105
+
97
106
  ## What this skill does not cover
98
107
 
99
108
  - Scotland, Wales, and Ireland beyond what Discovery holds for the whole UK catalogue.