@kinloom/cli 0.1.1 → 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 (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: hathitrust
3
+ description: Search HathiTrust Digital Library for out-of-copyright county histories, regimental rosters, and published genealogies via the bundled uv-based `hathi` CLI (no key needed), the catalog website, or the Data API with a key. Covers the Bibliographic API by identifier, catalog search URL patterns, rights (Full view vs Limited search-only), and worked examples. Use when checking whether a book is in HathiTrust, reading its rights and volume list, or finding a readable copy.
4
+ ---
5
+
6
+ # HathiTrust Digital Library
7
+
8
+ This skill includes a standalone executable Python CLI at `skills/hathitrust/scripts/hathi` using a PEP 723 `#!/usr/bin/env -S uv run --script` shebang with inline dependencies (`click`, `httpx`). No virtualenv setup or API key is required for the Bibliographic API or the catalog search URLs.
9
+
10
+ - **Bibliographic API (no key, no login):** returns bibliographic, rights, and volume information for a known identifier (OCLC, LCCN, ISBN, ISSN, HathiTrust ID, record number). This is what the CLI uses. It is identifier lookup only: it cannot keyword-search by title or author.
11
+ - **Catalog website (no login for searching):** keyword search by title, author, subject, or all fields. Use the `hathi url` command to build a verified search URL and open it in a browser.
12
+ - **Full-text search (login):** searching inside the text of volumes needs a partner-institution login or a free University of Michigan "Friend" account. The CLI does not cover it.
13
+ - **Data API (key needed):** page images, OCR text, and whole-volume packages need an access key from the Key Generation Service at `https://babel.hathitrust.org/cgi/kgs/request`. The CLI does not implement it; see below.
14
+
15
+ ## Bundled CLI (`scripts/hathi`)
16
+
17
+ Path: `skills/hathitrust/scripts/hathi` (note the short binary name `hathi`, not `hathitrust`).
18
+
19
+ ### Look up a record by identifier (Bibliographic API)
20
+
21
+ ```bash
22
+ # Official HathiTrust Bib API example (OCLC 424023)
23
+ skills/hathitrust/scripts/hathi bib oclc 424023
24
+
25
+ # Same record by its 9-digit HathiTrust record number
26
+ skills/hathitrust/scripts/hathi bib recordnumber 000578050
27
+
28
+ # One volume by its HathiTrust ID, with full MARC-XML
29
+ skills/hathitrust/scripts/hathi bib htid <htid> --full
30
+
31
+ # Several identifiers in one call (fetched one at a time, merged output)
32
+ skills/hathitrust/scripts/hathi bib --id oclc:424023 --id recordnumber:000578050
33
+
34
+ # Raw JSON exactly as the API returned it
35
+ skills/hathitrust/scripts/hathi bib oclc 424023 --json
36
+ ```
37
+
38
+ Identifier types: `oclc`, `lccn`, `issn`, `isbn`, `htid`, `recordnumber`. Values are URL-encoded by the CLI (LCCNs can contain spaces and slashes). A lookup that finds nothing prints empty `records` / `items` (the API returns `{ "records": {}, "items": [] }`, not an error), so check for that before concluding a title is absent under a different identifier.
39
+
40
+ Compact output keeps title, record URL, publish dates, identifiers, and for each item: originating library, HathiTrust ID, rights string, and item URL. `--full` adds the complete MARC-XML for the record.
41
+
42
+ ### Build a verified catalog search URL
43
+
44
+ ```bash
45
+ # Title search (open the printed URL in a browser)
46
+ skills/hathitrust/scripts/hathi url "Abraham Lincoln" --type title
47
+
48
+ # Author search
49
+ skills/hathitrust/scripts/hathi url "Douglass, Frederick" --type author
50
+
51
+ # Keyword search across all fields
52
+ skills/hathitrust/scripts/hathi url "Clara Barton" --type all
53
+ ```
54
+
55
+ This only prints the URL; it does not fetch results. Fetching catalog search HTML from a server is unreliable (Cloudflare challenges curl intermittently; see "Verified live"), so run the search in a real browser.
56
+
57
+ ## Website search and URL rules (verified live 2026-11-24)
58
+
59
+ - Catalog search: `https://catalog.hathitrust.org/Search/Home?lookfor=<query>&type=<type>&inst=`
60
+ - `lookfor` is the URL-encoded query. `type` is `all`, `title`, `author`, or `subject`. `inst=` is left empty when no partner institution is selected.
61
+ - Verified URL patterns:
62
+ - Author: `https://catalog.hathitrust.org/Search/Home?lookfor=%22Douglass%2C+Frederick%22&type=author&inst=`
63
+ - Subject: `https://catalog.hathitrust.org/Search/Home?lookfor=%22+Astrolabes%22&type=subject&inst=`
64
+ - `type=all` returned HTTP 200 with a results page in a live fetch on 2026-11-24. `type=title` is the catalog's field name for title search (per HathiTrust library guides) but a live fetch of a title search on the same day was met with a Cloudflare challenge (403), so treat `type=title` as documented and open it in a browser.
65
+ - Catalog record page: `https://catalog.hathitrust.org/Record/<9-digit-record-number>`, for example `https://catalog.hathitrust.org/Record/000578050`.
66
+ - Item (PageTurner) page: `https://babel.hathitrust.org/cgi/pt?id=<htid>`, or the persistent form `https://hdl.handle.net/2027/<htid>`.
67
+ - Search tips: use the catalog search for descriptive data (title, author, date); use full-text search for words inside a volume. Filter results by Full View to show only volumes readable online.
68
+
69
+ ## Bibliographic API reference (no key)
70
+
71
+ - Docs: `https://www.hathitrust.org/bib_api` and `https://www.hathitrust.org/member-libraries/resources-for-librarians/improve-discovery/integrate-records/`
72
+ - Brief: `https://catalog.hathitrust.org/api/volumes/brief/<id-type>/<id-value>.json`
73
+ - Full (adds complete MARC-XML): `https://catalog.hathitrust.org/api/volumes/full/<id-type>/<id-value>.json`
74
+ - Id types: `oclc` (digits only), `lccn`, `issn`, `isbn` (ISBN-10 is searched as both ISBN-10 and ISBN-13), `htid` (for example `mdp.39015058510069`), `recordnumber` (9-digit HathiTrust record number, also the `ht_bib_key` in the HathiFiles).
75
+ - Response shape: `records` keyed by record number (recordURL, titles, isbns, issns, oclcs, lccns, publishDates, plus `marc-xml` for full), and `items` (orig, fromRecord, htid, itemURL, rightsCode, lastUpdate, enumcron, usRightsString).
76
+ - Intended for small numbers of items at a time (multi-id form supports up to 20 records). Bulk retrieval uses OAI or the HathiFiles tab-delimited inventory files; do not bulk-scrape the Bib API.
77
+
78
+ ## Rights: what you can actually read
79
+
80
+ The `usRightsString` on each item decides readability:
81
+
82
+ - `Full view`: public domain (or otherwise open). Readable online by anyone, no login.
83
+ - `Limited (search-only)`: in copyright or undetermined. Searchable, but pages are not readable online without a partner-institution login.
84
+ - Common `rightsCode` values: `pd` (public domain), `pdus` (public domain in the US only), `ic` (in copyright), `und` (undetermined), `icus` (in copyright in the US), plus Creative Commons codes (`cc-by-4.0`, etc.).
85
+
86
+ Check the rights string before promising a readable copy. A title can be in HathiTrust and still not be readable online.
87
+
88
+ ## Data API (key needed, not in the CLI)
89
+
90
+ - Docs: `https://www.hathitrust.org/data_api` (Data API v2, revised 26 May 2015).
91
+ - What it returns: page images, OCR text, structural metadata, and in some cases whole-volume packages, plus metadata resources.
92
+ - Access: metadata resources are unrestricted; content (data) resources vary. Two routes: the web client at `https://babel.hathitrust.org/cgi/htdc` (needs login; non-members use a University of Michigan "Friend" account), or programmatic access with a key from the Key Generation Service at `https://babel.hathitrust.org/cgi/kgs/request`.
93
+ - URL scheme: `https://babel.hathitrust.org/cgi/htd/<resource>/<id>[/<fileid|seq>]`.
94
+ - The CLI does not implement the Data API. If a Full View volume is needed as OCR text, first try the item URL in a browser; request a key only if programmatic bulk access is genuinely needed.
95
+
96
+ ## Disk cache and environment variables
97
+
98
+ `bib` caches successful non-empty Bibliographic API lookups per identifier on disk under `~/.cache/kinloom-hathi/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors, non-JSON responses, and empty/error payloads are never cached.
99
+
100
+ - `--refresh`: bypass cached reads and write the fresh response to disk.
101
+ - `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
102
+ - `KINLOOM_HATHI_CACHE_DIR`: override the cache directory path.
103
+ - `KINLOOM_HATHI_CACHE_TTL_HOURS`: override the default TTL in hours.
104
+
105
+ No API key or login is needed for the Bibliographic API.
106
+
107
+ ## Research workflow notes
108
+
109
+ - **County histories and regimental rosters:** these are usually pre-1929 and therefore often `Full view`. Search the catalog by title or subject, then confirm `usRightsString` is `Full view` with `hathi bib` before linking a readable copy. Use the HathiTrust record number as the stable citation, not the item URL alone, since items are per-scan.
110
+ - **Check WorldCat OCLC numbers carefully:** do not assume a title is in HathiTrust from a WorldCat listing alone, because WorldCat OCLC numbers and HathiTrust holdings differ. Confirm any hit with `hathi bib` before citing it; if HathiTrust returns empty records, check Internet Archive (`archive-org` skill) for an alternate scan.
111
+
112
+ ## Verified live 2026-11-24
113
+
114
+ - Bib API brief `oclc/424023` returns 200 JSON: record `000578050`, "Infinite series", 1962 (the documentation's own example).
115
+ - Bib API full `oclc/424023` returns 200 JSON including `marc-xml`.
116
+ - Catalog search `type=all` returned 200 HTML in one live fetch; subsequent fetches of catalog search pages and record pages returned 403 Cloudflare challenge pages (about 5.7 KB). The Bib API was reliable on every attempt; catalog HTML was not. That is why the CLI looks records up through the Bib API and only builds catalog search URLs for a real browser instead of scraping result pages.
117
+ - Full-text Large Scale Search (`https://babel.hathitrust.org/cgi/ls?a=srchls&q1=...`) returns 403 unauthenticated, so full-text search is documented as login-only and is not in the CLI.
@@ -0,0 +1,379 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "click>=8.1",
6
+ # "httpx>=0.27",
7
+ # ]
8
+ # ///
9
+ """Compact CLI for HathiTrust Digital Library lookups.
10
+
11
+ Uses the public Bibliographic API (no key, no login) to look up records by
12
+ identifier, and builds verified catalog search URLs for a real browser.
13
+ The Bib API is identifier lookup only: it cannot keyword-search.
14
+ Catalog search HTML is not scraped: HathiTrust serves Cloudflare
15
+ challenges to server-side fetches intermittently, so `url` prints a
16
+ search URL instead of fetching results.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import math
24
+ import os
25
+ import time
26
+ from contextlib import contextmanager
27
+ from pathlib import Path
28
+ from typing import Any, Callable, Iterator
29
+ from urllib.parse import quote, urlencode
30
+
31
+ import click
32
+ import httpx
33
+
34
+ DEFAULT_CACHE_TTL_HOURS = 168.0
35
+ CACHE_SCHEMA = 1
36
+
37
+ BIB_API_BASE = "https://catalog.hathitrust.org/api/volumes"
38
+ CATALOG_SEARCH_BASE = "https://catalog.hathitrust.org/Search/Home"
39
+ USER_AGENT = (
40
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
41
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
42
+ )
43
+ VALID_ID_TYPES = ("oclc", "lccn", "issn", "isbn", "htid", "recordnumber")
44
+ VALID_SEARCH_TYPES = ("all", "title", "author", "subject")
45
+
46
+
47
+ def cache_dir() -> Path:
48
+ override = os.environ.get("KINLOOM_HATHI_CACHE_DIR")
49
+ if override:
50
+ return Path(override).expanduser()
51
+ return Path.home() / ".cache" / "kinloom-hathi"
52
+
53
+
54
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
55
+ if cli_ttl is not None:
56
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
57
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
58
+ return float(cli_ttl)
59
+ raw = os.environ.get("KINLOOM_HATHI_CACHE_TTL_HOURS")
60
+ if raw is not None and raw.strip():
61
+ try:
62
+ parsed = float(raw.strip())
63
+ except ValueError as exc:
64
+ raise click.BadParameter(f"Invalid KINLOOM_HATHI_CACHE_TTL_HOURS value: {raw!r}.") from exc
65
+ if not math.isfinite(parsed) or parsed < 0:
66
+ raise click.BadParameter(
67
+ f"Invalid KINLOOM_HATHI_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
68
+ )
69
+ return parsed
70
+ return DEFAULT_CACHE_TTL_HOURS
71
+
72
+
73
+ @contextmanager
74
+ def file_lock(lock_path: Path) -> Iterator[None]:
75
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
76
+ try:
77
+ import fcntl
78
+ except ImportError:
79
+ yield
80
+ return
81
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
82
+ with open(lock_path, "a+b") as lock_file:
83
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
84
+ try:
85
+ yield
86
+ finally:
87
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
88
+
89
+
90
+ def atomic_write_json(dest: Path, payload: Any) -> None:
91
+ dest.parent.mkdir(parents=True, exist_ok=True)
92
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
93
+ try:
94
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
95
+ os.replace(tmp, dest)
96
+ except Exception:
97
+ tmp.unlink(missing_ok=True)
98
+ raise
99
+
100
+
101
+ def cache_key(kind: str, payload: dict) -> str:
102
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
103
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
104
+
105
+
106
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
107
+ if not path.is_file():
108
+ return None
109
+ try:
110
+ entry = json.loads(path.read_text(encoding="utf-8"))
111
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
112
+ return None
113
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
114
+ return None
115
+ fetched = entry.get("fetched_at")
116
+ if not isinstance(fetched, (int, float)):
117
+ return None
118
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
119
+ return None
120
+ result = entry.get("result")
121
+ return result if isinstance(result, dict) else None
122
+
123
+
124
+ def cached_call(
125
+ kind: str,
126
+ payload: dict,
127
+ fetch: Callable[[], dict],
128
+ *,
129
+ refresh: bool,
130
+ ttl_hours: float,
131
+ cacheable: Callable[[dict], bool] = lambda _r: True,
132
+ ) -> tuple[dict, bool]:
133
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
134
+ key = cache_key(kind, payload)
135
+ root = cache_dir()
136
+ path = root / f"{key}.json"
137
+ if not refresh:
138
+ hit = read_cache(path, ttl_hours)
139
+ if hit is not None:
140
+ return hit, True
141
+ with file_lock(root / f"{key}.lock"):
142
+ if not refresh:
143
+ hit = read_cache(path, ttl_hours)
144
+ if hit is not None:
145
+ return hit, True
146
+ result = fetch()
147
+ if cacheable(result):
148
+ atomic_write_json(
149
+ path,
150
+ {
151
+ "schema": CACHE_SCHEMA,
152
+ "fetched_at": time.time(),
153
+ "kind": kind,
154
+ "query": payload,
155
+ "result": result,
156
+ },
157
+ )
158
+ return result, False
159
+
160
+
161
+ def cache_options(func: Callable) -> Callable:
162
+ func = click.option(
163
+ "--cache-ttl-hours",
164
+ type=float,
165
+ default=None,
166
+ help="Cache TTL in hours (default 168, env KINLOOM_HATHI_CACHE_TTL_HOURS; 0 disables reads).",
167
+ )(func)
168
+ func = click.option(
169
+ "--refresh",
170
+ is_flag=True,
171
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
172
+ )(func)
173
+ return func
174
+
175
+
176
+ def _client() -> httpx.Client:
177
+ return httpx.Client(headers={"User-Agent": USER_AGENT})
178
+
179
+
180
+ def _bib_cacheable(data: dict) -> bool:
181
+ if not isinstance(data, dict) or data.get("error"):
182
+ return False
183
+ records = data.get("records")
184
+ items = data.get("items")
185
+ if not isinstance(records, dict) or not isinstance(items, list):
186
+ return False
187
+ return bool(records) or bool(items)
188
+
189
+
190
+ def bib_url(id_type: str, value: str, full: bool) -> str:
191
+ brevity = "full" if full else "brief"
192
+ return f"{BIB_API_BASE}/{brevity}/{id_type}/{quote(value, safe='')}.json"
193
+
194
+
195
+ def fetch_bib(client: httpx.Client, id_type: str, value: str, full: bool) -> dict:
196
+ url = bib_url(id_type, value, full)
197
+ try:
198
+ resp = client.get(url, timeout=30.0)
199
+ resp.raise_for_status()
200
+ except httpx.HTTPStatusError as exc:
201
+ raise click.ClickException(
202
+ f"Bib API request failed ({exc.response.status_code}): {url}"
203
+ ) from exc
204
+ except httpx.HTTPError as exc:
205
+ raise click.ClickException(f"Bib API request failed: {exc}") from exc
206
+ try:
207
+ data = resp.json()
208
+ except ValueError as exc:
209
+ raise click.ClickException(f"Bib API returned non-JSON for {url}") from exc
210
+ if not isinstance(data, dict):
211
+ raise click.ClickException(f"Bib API returned unexpected JSON shape for {url}")
212
+ return data
213
+
214
+
215
+ def parse_id(spec: str) -> tuple[str, str]:
216
+ if ":" not in spec:
217
+ raise click.BadParameter(
218
+ f"Bad identifier {spec!r}. Use type:value, e.g. oclc:424023."
219
+ )
220
+ id_type, value = spec.split(":", 1)
221
+ id_type = id_type.strip().lower()
222
+ value = value.strip()
223
+ if id_type not in VALID_ID_TYPES or not value:
224
+ raise click.BadParameter(
225
+ f"Bad identifier {spec!r}. Type must be one of: "
226
+ f"{', '.join(VALID_ID_TYPES)}."
227
+ )
228
+ return id_type, value
229
+
230
+
231
+ def compact_bib(data: dict, full: bool, *, cache_hit: bool = False) -> str:
232
+ marker = " [cache]" if cache_hit else ""
233
+ lines: list[str] = []
234
+ records = data.get("records") or {}
235
+ items = data.get("items") or []
236
+ if not records and not items:
237
+ return f"No matching HathiTrust record (empty records and items).{marker}"
238
+ first = True
239
+ for rec_no, rec in records.items():
240
+ titles = rec.get("titles") or []
241
+ suffix = marker if first else ""
242
+ first = False
243
+ lines.append(f"Record {rec_no}: {titles[0] if titles else '(no title)'}{suffix}")
244
+ if len(titles) > 1:
245
+ lines.append(f" alt titles: {'; '.join(titles[1:])}")
246
+ lines.append(f" record URL: {rec.get('recordURL', '')}")
247
+ if rec.get("publishDates"):
248
+ lines.append(f" published: {', '.join(rec['publishDates'])}")
249
+ for field in ("oclcs", "lccns", "isbns", "issns"):
250
+ if rec.get(field):
251
+ lines.append(f" {field}: {', '.join(rec[field])}")
252
+ if full and rec.get("marc-xml"):
253
+ lines.append(" marc-xml:")
254
+ lines.append(rec["marc-xml"])
255
+ for item in items:
256
+ suffix = marker if first else ""
257
+ first = False
258
+ lines.append(
259
+ f"Item {item.get('htid', '')} ({item.get('orig', '')}): "
260
+ f"{item.get('usRightsString', '')}{suffix}"
261
+ )
262
+ lines.append(f" item URL: {item.get('itemURL', '')}")
263
+ if item.get("enumcron"):
264
+ lines.append(f" enumcron: {item['enumcron']}")
265
+ if item.get("rightsCode"):
266
+ lines.append(f" rights code: {item['rightsCode']}")
267
+ return "\n".join(lines)
268
+
269
+
270
+ @click.group()
271
+ def cli() -> None:
272
+ """HathiTrust Digital Library lookups (Bibliographic API, no key)."""
273
+
274
+
275
+ @cli.command()
276
+ @click.argument("id_type", required=False)
277
+ @click.argument("value", required=False)
278
+ @click.option(
279
+ "--id",
280
+ "ids",
281
+ multiple=True,
282
+ help="Identifier as type:value, e.g. oclc:424023. Repeatable.",
283
+ )
284
+ @click.option("--full", is_flag=True, help="Full record with MARC-XML.")
285
+ @click.option("--json", "as_json", is_flag=True, help="Print raw API JSON.")
286
+ @cache_options
287
+ def bib(
288
+ id_type: str | None,
289
+ value: str | None,
290
+ ids: tuple[str, ...],
291
+ full: bool,
292
+ as_json: bool,
293
+ refresh: bool,
294
+ cache_ttl_hours: float | None,
295
+ ) -> None:
296
+ """Look up record(s) by identifier.
297
+
298
+ ID_TYPE is one of oclc, lccn, issn, isbn, htid, recordnumber.
299
+
300
+ Examples:\n
301
+ hathi bib oclc 424023\n
302
+ hathi bib recordnumber 000578050\n
303
+ hathi bib --id oclc:424023 --id recordnumber:000578050
304
+ """
305
+ specs: list[tuple[str, str]] = []
306
+ if ids:
307
+ specs = [parse_id(spec) for spec in ids]
308
+ elif id_type and value:
309
+ id_type = id_type.strip().lower()
310
+ if id_type not in VALID_ID_TYPES:
311
+ raise click.BadParameter(
312
+ f"Invalid id type {id_type!r}. Choose from: "
313
+ f"{', '.join(VALID_ID_TYPES)}"
314
+ )
315
+ specs = [(id_type, value.strip())]
316
+ else:
317
+ raise click.UsageError(
318
+ "Give an identifier: hathi bib <type> <value> "
319
+ "or hathi bib --id type:value [--id type:value ...]"
320
+ )
321
+ ttl = resolve_ttl_hours(cache_ttl_hours)
322
+ merged: dict[str, Any] = {"records": {}, "items": []}
323
+ hits: list[bool] = []
324
+ client: httpx.Client | None = None
325
+ try:
326
+ for spec_type, spec_value in specs:
327
+ def _fetch(t: str = spec_type, v: str = spec_value) -> dict:
328
+ nonlocal client
329
+ if client is None:
330
+ client = _client()
331
+ return fetch_bib(client, t, v, full)
332
+
333
+ data, hit = cached_call(
334
+ "bib",
335
+ {"id_type": spec_type, "value": spec_value, "full": full},
336
+ _fetch,
337
+ refresh=refresh,
338
+ ttl_hours=ttl,
339
+ cacheable=_bib_cacheable,
340
+ )
341
+ hits.append(hit)
342
+ merged["records"].update(data.get("records") or {})
343
+ merged["items"].extend(data.get("items") or [])
344
+ finally:
345
+ if client is not None:
346
+ client.close()
347
+ all_cached = bool(hits) and all(hits)
348
+ if as_json:
349
+ click.echo(json.dumps({**merged, "cache_hit": all_cached}, indent=2, ensure_ascii=False))
350
+ else:
351
+ click.echo(compact_bib(merged, full, cache_hit=all_cached))
352
+
353
+
354
+ @cli.command()
355
+ @click.argument("query")
356
+ @click.option(
357
+ "--type",
358
+ "search_type",
359
+ default="all",
360
+ show_default=True,
361
+ type=click.Choice(VALID_SEARCH_TYPES),
362
+ help="Catalog search field.",
363
+ )
364
+ def url(query: str, search_type: str) -> None:
365
+ """Print a verified catalog search URL for QUERY (open in a browser).
366
+
367
+ Examples:\n
368
+ hathi url "Abraham Lincoln" --type title\n
369
+ hathi url "Douglass, Frederick" --type author
370
+ """
371
+ params = urlencode(
372
+ {"lookfor": query, "type": search_type, "inst": ""},
373
+ quote_via=quote,
374
+ )
375
+ click.echo(f"{CATALOG_SEARCH_BASE}?{params}")
376
+
377
+
378
+ if __name__ == "__main__":
379
+ cli()
@@ -0,0 +1,124 @@
1
+ ---
2
+ name: kentucky-archives
3
+ description: Research historical and genealogical records in Kentucky through the Kentucky Historical Society (KHS) Digital Collections, the Kentucky Department for Libraries and Archives (KDLA) Preservica e-archives, and the Kentucky Secretary of State Land Office patent databases, using the bundled `ky-archives` CLI. Covers CONTENTdm surname and collection search, Confederate pension packets, County Court Orders patents (1835-2000), Virginia and Old Kentucky patents, and what is browser-only or visit-only. Use when tracing ancestors from Virginia into Kentucky, finding Kentucky land patents, family papers, photographs, oral histories, or a Confederate pension packet, or deciding whether a Kentucky record is online, orderable, or visit-only.
4
+ ---
5
+
6
+ # Kentucky Archives
7
+
8
+ Kentucky has three primary repositories for genealogical research, and they hold different collections. Do not treat them as one repository.
9
+
10
+ This skill includes a standalone executable Python CLI at `skills/kentucky-archives/scripts/ky-archives` using a PEP 723 `#!/usr/bin/env -S uv run --script` shebang with inline dependencies (`click`, `httpx`). No virtualenv setup or API key is needed. Run it from the repo root, for example `./skills/kentucky-archives/scripts/ky-archives cdm Lincoln`.
11
+
12
+ ## Bundled CLI (`scripts/ky-archives`)
13
+
14
+ | Command | What it does | Interface (verified live 2026-11-24) |
15
+ |---|---|---|
16
+ | `cdm <query> [--collection ALIAS] [--field FIELD] [--limit N] [--json]` | Search KHS Digital Collections | CONTENTdm dmwebservices API, key-free: `GET https://www.kyhistory.com/digital/api/search/collection/<alias>/searchterm/<term>/field/<field>/maxRecords/<n>` |
17
+ | `cdm-item <alias> <id> [--json]` | Full metadata for one CONTENTdm item | `GET https://www.kyhistory.com/digital/api/singleitem/collection/<alias>/id/<id>` |
18
+ | `collections [--json]` | List the 16 CONTENTdm collections and aliases | `GET https://www.kyhistory.com/digital/api/collections` |
19
+ | `cdm-url <query>` | Print the verified catalog web search URL (no request) | `https://www.kyhistory.com/cdm/search/searchterm/<term>/mode/exact` |
20
+ | `land <term> [--by grantee\|county\|watercourse\|survey-name\|survey-year\|grant-year\|patent\|warrant\|grant-book] [--limit 10\|25\|50\|100] [--json]` | Advanced search, County Court Orders patents | ASP.NET form POST to `https://web.sos.ky.gov/land/ccorders.aspx` (GET state, postback to open the advanced panel, POST the search) |
21
+ | `land-patent <number> [--book N] [--page N] [--json]` | Quick search by patent number (or grant book/page) | Same ASP.NET form, quick-search fields |
22
+ | `preservica <query> [--limit N] [--json]` | Search KDLA Preservica e-archives | WordPress search RSS feed: `GET https://kdla.access.preservica.com/search/<term>/feed/rss2/`; human search page is `https://kdla.access.preservica.com/?s=<term>` |
23
+ | `urls <query>` | Print every verified Kentucky search URL (no requests) | See the URLs in the sections below |
24
+
25
+ Notes on the interfaces:
26
+
27
+ - The CONTENTdm API returns `totalResults` and items with `collectionAlias`, `itemId`, `title`, `filetype`, `itemLink`, and `metadataFields`. The API's `itemLink` has no `/digital` prefix; the CLI adds it, because the bare link (`https://www.kyhistory.com/singleitem/...`) returns 403 from OCLC, while the `/digital/...` form returns 200 (verified live 2026-11-24).
28
+ - The KHS web UI returns 403 to a bare Linux-Chrome user agent and 200 to a Windows Chrome user agent. The CLI sends a Windows Chrome UA on every request for that reason. The CONTENTdm API itself accepts either.
29
+ - The Land Office form is ASP.NET with `__VIEWSTATE`/`__EVENTVALIDATION`; the CLI does the three-request dance (GET, postback to reveal the advanced panel, search POST) and parses the results table into patent, grantee, grant book/page, acreage, county, watercourse, survey name, survey/grant dates, and grant note.
30
+ - The Preservica host has no public Preservica search API (`/wp-json/` returns a Preservica "Page Not Found" page). The WordPress search RSS feed is the machine route; it returns up to 100 items per query. The site's search is full-text over titles, descriptions, creators, and document contents, so a hit's title often does not show why it matched: open the hit to confirm. Viewing a packet's scans needs the browser.
31
+ - No account or API key is needed to search any portal in this skill. Fees apply only to ordering copies, noted per repository below.
32
+ - **Disk cache:** `cdm`, `cdm-item`, `collections`, `land`, `land-patent`, and `preservica` cache successful responses under `~/.cache/kinloom-ky-archives/` (default TTL `168` hours, per-key `flock`, atomic JSON writes). Pass `--refresh` to force a fresh fetch or `--cache-ttl-hours <hours>` (`0` disables reads). Override with `KINLOOM_KY_ARCHIVES_CACHE_DIR` and `KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS`. HTTP errors and unverified 0-hit error pages are never cached.
33
+
34
+ ## Kentucky Historical Society (KHS)
35
+
36
+ Portal: https://history.ky.gov/
37
+ Digital collections catalog: https://www.kyhistory.com/
38
+ Research and genealogy starting page: https://history.ky.gov/research-genealogy
39
+ Address: Thomas D. Clark Center for Kentucky History, 100 West Broadway, Frankfort, KY 40601. The Martin F. Schmidt Research Library on the second floor holds the largest genealogical collection in the state: over 16,000 rolls of microfilm, 90,000 books and periodicals, 30,000 vertical files, 1,900 cubic feet of manuscripts, 2,000 maps, 8,000 oral histories, and 200,000 historic photographs.
40
+
41
+ KHS Digital Collections is a searchable database of digital images and files from KHS collections: print, archival, graphic, audio, and video files, plus finding aids, photographs, oral histories, and manuscripts. It runs on CONTENTdm (16 collections, including Manuscripts `MS`, Resources and Finding Aids `LIB`, Printed Materials `RB`, Visual Materials `PH`, Maps and Atlases `Maps`, Kentucky Ancestors `p16602coll3`, and Oral History `Ohist`).
42
+
43
+ ```bash
44
+ # Surname search across all collections
45
+ skills/kentucky-archives/scripts/ky-archives cdm Lincoln
46
+ # Manuscripts only
47
+ skills/kentucky-archives/scripts/ky-archives cdm Lincoln --collection MS --limit 25
48
+ # Full metadata for one hit
49
+ skills/kentucky-archives/scripts/ky-archives cdm-item <alias> <item-id>
50
+ ```
51
+
52
+ The verified web search pattern, from KHS's own research blog, is `https://www.kyhistory.com/cdm/search/searchterm/<term>/mode/exact`, for example `https://www.kyhistory.com/cdm/search/searchterm/SC%201261/mode/exact` for a manuscript collection. Use it for a known collection number or a distinctive term; for a surname use the CLI or the catalog's surname search, which searches all manuscript collections and family histories at once.
53
+
54
+ Other KHS online tools:
55
+
56
+ - Pass the Word: a discovery tool for oral history collections across the Commonwealth, sponsored by the Kentucky Oral History Commission. Over 25,000 interviews from more than 100 archives, searchable by interviewee name and topic. Browser only, no machine interface found: https://passtheword.ky.gov/ (returned 200 live 2026-11-24).
57
+ - Kentucky Ancestors back issues, Vol. 1 (July 1965) through Vol. 48 (Summer 2013), digitized as PDFs through the Digital Collections Catalog (collection `p16602coll3`). Not indexed as of the KHS notice; search within each issue PDF.
58
+ - Civil War Governors of Kentucky Digital Documentary Edition, a KHS digital humanities project.
59
+ - The Register, the KHS scholarly journal, is available through Project Muse and JSTOR, not free on the KHS site.
60
+
61
+ What is in-person only at KHS: most manuscript collections are described in the catalog but only partly digitized. Ancestry.com Library Edition, HeritageQuest, American Periodicals 1740-1940, and the Louisville Courier-Journal 1830-1922 are free on site in the research library, not remotely. Copies can be ordered for a fee.
62
+
63
+ ## Kentucky Department for Libraries and Archives (KDLA), Kentucky State Archives
64
+
65
+ Portal: https://kdla.ky.gov/
66
+ E-archives (Preservica): https://kdla.access.preservica.com/
67
+
68
+ KDLA is the state archives proper. Its e-archives hold state government records including the Confederate pension files. Older guidance says KDLA search results often tell you where a document is filed and you then order a copy for a fee, rather than showing the whole document online. That is now only partly true: the Preservica e-archives do show scanned pension packets online.
69
+
70
+ ```bash
71
+ # Search the e-archives (full-text; open hits to confirm the match)
72
+ skills/kentucky-archives/scripts/ky-archives preservica Lincoln --limit 10
73
+ ```
74
+
75
+ Confederate Pension Application Packets are browsable in Preservica in numbered folders (for example packets 1526-1550, 2001-2025, 1101-1125), each packet a scanned application by a soldier or a widow, filed starting in 1912 when Kentucky began granting Confederate pensions. Search by surname to locate relevant packets, then view the scanned packet in a browser.
76
+
77
+ ## Kentucky Secretary of State, Land Office
78
+
79
+ Portal: https://www.sos.ky.gov/land/Pages/default.aspx
80
+ County Court Orders patents search: https://web.sos.ky.gov/land/ccorders.aspx
81
+
82
+ The Land Office is the repository for all Kentucky land patents, including those issued by Virginia before Kentucky statehood in 1792. Because Kentucky is not a federal public-land state, early Kentucky land ownership is proved through Virginia warrants and Kentucky state patents rather than federal BLM GLO patents.
83
+
84
+ Searchable online, verified 2026-11-24:
85
+
86
+ - Virginia Patent Series and Old Kentucky Patent Series: searchable by patent number or grantee. These cover patents finalized by Virginia grants before 1792 and the 7,771 Old Kentucky patents. Many patent files link to scanned color images. Related warrant databases are also searchable by name: Virginia Treasury Warrants (search by warrant number or by last name, first name), Revolutionary War Warrants, Lincoln Entries, Certificates of Settlement, and Preemption Warrants.
87
+ - County Court Orders series: 70,241 patents, 1835-2000, the largest series. Quick search by patent number (5 digits) or book and page; advanced search by county, watercourse, grant name, survey name, survey year, and grant year. Some patent numbers 0001.0-8241.0 link to scanned images of patent files.
88
+ - West of Tennessee River Military Patents: 242 patents, with scanned images of warrants, entries, surveys, and grants. West of Tennessee River Non-Military Patents: over 8,500 patent files with scanned images, plus a Jackson Purchase Locator.
89
+
90
+ ```bash
91
+ # Grantee search in the County Court Orders series (the CLI's `land` command)
92
+ skills/kentucky-archives/scripts/ky-archives land Lincoln --by grantee
93
+ # Other fields: --by county, --by watercourse, --by survey-year, --by grant-year
94
+ skills/kentucky-archives/scripts/ky-archives land Hardin --by county --limit 25
95
+ # Quick search by patent number
96
+ skills/kentucky-archives/scripts/ky-archives land-patent <patent-number>
97
+ ```
98
+
99
+ Not online: the South of Green River, Tellico, Kentucky Land Warrants, South of Walker's Line, and Warrants for Headrights series are not available online as of the Land Office's own series summary. Request those files by online order form or email to the Land Office, using Jillson's *The Kentucky Land Grants* to determine grantee, patent series, and citation first. Copies of grants can also be ordered from the KHS library and KDLA in Frankfort.
100
+
101
+ Browser only, no machine interface: the Virginia / Old Kentucky Patent Series browser at `https://web.sos.ky.gov/land/vakypatentseries.aspx` is a series dropdown plus a patent list (verified live 2026-11-24: series options are Virginia Patent Series and Old Kentucky Patent Series; there is no name search field). Use it in the browser to browse a series by patent number once the CLI or Jillson gives you the citation.
102
+
103
+ ## Kentucky vital records
104
+
105
+ Kentucky has no statewide vital-records database at KHS or KDLA. The University of Kentucky's Kentucky Vital Records Index covers deaths 1911-1992, marriages 1973-1993, and divorces 1973-1993. Earlier Kentucky vital events are in county records, church records, and subscription indexes. Do not expect the state archives to produce a Kentucky birth or marriage certificate. Note: the index's old URL `http://ukcc.uky.edu/vitalrec/` did not resolve live 2026-11-24, so no URL is given here; find the current index through the University of Kentucky Libraries site. Inferred, not verified: FamilySearch's Kentucky, Vital Record Indexes, 1911-1999 collection covers much of the same ground.
106
+
107
+ ## Research workflow
108
+
109
+ For families migrating into Kentucky from Virginia, check repositories in this order:
110
+
111
+ 1. Land Office Virginia and Old Kentucky Patent Series by grantee surname (this proves early land ownership and often names assignees and warrant holders).
112
+ 2. County Court Orders series (`ky-archives land <surname> --by grantee`) if the family held or acquired land after 1835.
113
+ 3. KHS Digital Collections (`ky-archives cdm <surname>`) for family papers, county indexes, and photographs.
114
+ 4. KDLA Preservica (`ky-archives preservica <surname>`) for Confederate pension packets and state agency files.
115
+ 5. Record the patent series, patent number, and survey year for every hit; the same individual often appears under both a Virginia warrant and a Kentucky patent.
116
+
117
+ ## Verification log (verified live 2026-11-24)
118
+
119
+ - `history.ky.gov` and `kdla.ky.gov` returned 200; `kyhistory.com` returned 200 to a Windows Chrome UA (403 to a bare Linux-Chrome UA); `kdla.access.preservica.com` returned 200; `web.sos.ky.gov/land/ccorders.aspx` and `www.sos.ky.gov/land/Pages/default.aspx` returned 200.
120
+ - CONTENTdm API: `/digital/api/collections` returned 16 collections; `/digital/api/search/...` and `/digital/api/singleitem/...` returned full JSON metadata. Item links verified: `/digital/singleitem/...` 200, `/digital/compoundobject/...` 200, bare `/singleitem/...` 403.
121
+ - Land Office: advanced search POST and quick search by patent number returned parsed results tables through the CLI.
122
+ - Preservica: WordPress search RSS feed returned up to 100 items per query; `/wp-json/` returned a Preservica "Page Not Found" page, confirming no public Preservica search API on this host.
123
+ - Pass the Word `https://passtheword.ky.gov/` returned 200. The UK Vital Records Index old URL `http://ukcc.uky.edu/vitalrec/` did not resolve (connection failure). The Virginia / Old Kentucky Patent Series page `vakypatentseries.aspx` returned 200 and shows series + patent dropdowns only.
124
+ - KDLA Preservica Confederate pension packets and Land Office patent series counts (County Court Orders 70,241 patents 1835-2000; 7,771 Old Kentucky patents) were confirmed on 2026-11-24.