@kinloom/cli 0.3.1 → 0.4.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.
- package/dist/bundled-skills/chronicling-america/SKILL.md +9 -7
- package/dist/bundled-skills/chronicling-america/scripts/chronam +139 -16
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +20 -2
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +295 -0
- package/dist/client.js +1 -1
- package/package.json +2 -2
|
@@ -10,7 +10,7 @@ This skill includes a standalone executable Python CLI at `skills/chronicling-am
|
|
|
10
10
|
- **Coverage:** millions of digitized U.S. newspaper pages, 1736 through 1963 (per the collection record; the site describes it as "through 1963").
|
|
11
11
|
- **Access:** the public loc.gov JSON API. No key, no account, no sign-in.
|
|
12
12
|
- **Latency (measured 2026-11-25):** every loc.gov collection search takes **20-45 s** on the server side. Connect + TLS take under 0.1 s, but time-to-first-byte was 19-43 s for every query shape tried (with or without `q`, `dates`, `fa=location_state`, `dl=page`, `at=results` vs `at=search,results`, HTTP/1.1 vs HTTP/2, kinloom vs browser User-Agent). One probe under 6 parallel requests took 70 s. The old 8 s default timeout therefore failed 80%+ of searches. The default `--timeout` is now **120 s**. `/newspapers/?fo=json` returned 0 hits for the same query, and `/search/?fa=partof:chronicling+america` 302-redirects to the collection endpoint, so neither is faster.
|
|
13
|
-
- **Disk cache:** every successful search
|
|
13
|
+
- **Disk cache:** every successful search, every `get` item record, and every `download` file is cached, so a repeat returns with no network call. See [Disk cache](#disk-cache).
|
|
14
14
|
- **Rate limits:** be gentle. LoC asks users to stay within limits; search queries returning more than 100,000 results are too big for the API, so narrow with `--dates`, `--state`, or `--lccn` first. The CLI retries HTTP 429/503 once after the `Retry-After` delay (capped at 30 s) and retries 5xx and dropped connections once.
|
|
15
15
|
- **Unstable hit counts (measured 2026-11-25):** loc.gov can return very different `hits` for byte-identical requests. `Merced` + California + 1900/1920 returned 32, then 34,133, then 35,404. `Abraham Lincoln` returned 0, then 25,392, then 77,301. So a low or zero count is **not** evidence of absence. The CLI never caches a zero-hit answer. To recheck a suspiciously low count, rerun with `--refresh`.
|
|
16
16
|
|
|
@@ -46,11 +46,13 @@ Options: `--dates YYYY/YYYY` or `YYYY` (or `--date-from`/`--from-year`/`--date1`
|
|
|
46
46
|
|
|
47
47
|
### Disk cache
|
|
48
48
|
|
|
49
|
-
- Location: `~/.cache/kinloom-chronam/` (override with `KINLOOM_CHRONAM_CACHE_DIR`).
|
|
50
|
-
-
|
|
51
|
-
- `--
|
|
52
|
-
-
|
|
53
|
-
-
|
|
49
|
+
- Location: `~/.cache/kinloom-chronam/` (override with `KINLOOM_CHRONAM_CACHE_DIR`).
|
|
50
|
+
- Search and `get` store one JSON file per request, keyed by the SHA-256 of the URL and sorted query parameters.
|
|
51
|
+
- `download` stores each HTTPS file under `files/<sha256>.bin` with a sidecar `files/<sha256>.json`. A cache hit copies those bytes to `--out` and does not open a connection. Output names are a single path segment, so a date or LCCN that contains `..` or a slash cannot write outside `--out`.
|
|
52
|
+
- TTL: 168 hours (override with `--cache-ttl-hours` or `KINLOOM_CHRONAM_CACHE_TTL_HOURS`; `0` disables reads). The same TTL covers search JSON, `get` JSON, and downloaded files.
|
|
53
|
+
- `--refresh` re-queries loc.gov and rewrites the entry, including downloaded files.
|
|
54
|
+
- Zero-hit search answers are never cached (see unstable hit counts above). Empty downloads are not cached.
|
|
55
|
+
- Writes are atomic (temp file + rename). A per-key `flock` makes concurrent agents that run the same request wait for the first one and then read its file, so loc.gov sees one request.
|
|
54
56
|
|
|
55
57
|
### Inspect one page
|
|
56
58
|
|
|
@@ -74,7 +76,7 @@ skills/chronicling-america/scripts/chronam download --lccn sn83045462 --date 186
|
|
|
74
76
|
skills/chronicling-america/scripts/chronam download --lccn sn83045462 --date 1865-04-15 --seq 1 --out ./downloads/chronam --text --image
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
Files are named `<lccn>_<date>_sp<seq>.pdf` (etc.) with a matching `<stem>.metadata.json`.
|
|
79
|
+
Files are named `<lccn>_<date>_sp<seq>.pdf` (etc.) with a matching `<stem>.metadata.json`. The first download fetches the file. The next download of the same URL copies it from `~/.cache/kinloom-chronam/files/` and makes no HTTP request. `--refresh` fetches again. A hit line ends with `[cache]`.
|
|
78
80
|
|
|
79
81
|
### Build a website search URL
|
|
80
82
|
|
|
@@ -151,6 +151,122 @@ def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
|
151
151
|
return data if isinstance(data, dict) else None
|
|
152
152
|
|
|
153
153
|
|
|
154
|
+
def atomic_write_bytes(dest: Path, data: bytes) -> None:
|
|
155
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
156
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
157
|
+
try:
|
|
158
|
+
tmp.write_bytes(data)
|
|
159
|
+
os.replace(tmp, dest)
|
|
160
|
+
except Exception:
|
|
161
|
+
tmp.unlink(missing_ok=True)
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def resolve_safe_child(root: Path, filename: str) -> Path:
|
|
166
|
+
"""Resolve one filename strictly inside root."""
|
|
167
|
+
if (
|
|
168
|
+
not filename
|
|
169
|
+
or "\x00" in filename
|
|
170
|
+
or "/" in filename
|
|
171
|
+
or "\\" in filename
|
|
172
|
+
or ":" in filename
|
|
173
|
+
or filename in (".", "..")
|
|
174
|
+
or ".." in filename
|
|
175
|
+
):
|
|
176
|
+
raise click.ClickException(f"Unsafe filename: {filename!r}")
|
|
177
|
+
root_resolved = root.resolve()
|
|
178
|
+
dest = (root_resolved / filename).resolve()
|
|
179
|
+
if dest == root_resolved or not dest.is_relative_to(root_resolved):
|
|
180
|
+
raise click.ClickException(f"Unsafe path escaping {root}: {filename!r}")
|
|
181
|
+
return dest
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def safe_output_filename(raw: str) -> str:
|
|
185
|
+
"""Turn an output name into one path segment. Reject traversal."""
|
|
186
|
+
candidate = (raw or "").replace("\\", "/")
|
|
187
|
+
base = candidate.rsplit("/", 1)[-1].strip().replace("..", "_")
|
|
188
|
+
base = re.sub(r"[^A-Za-z0-9._-]+", "_", base).strip("._")
|
|
189
|
+
if not base or base in {".", ".."} or ".." in base or "/" in base or "\\" in base:
|
|
190
|
+
base = "page.bin"
|
|
191
|
+
return base
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _file_cache_paths(url: str) -> tuple[Path, Path, Path]:
|
|
195
|
+
key = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
|
196
|
+
root = cache_dir() / "files"
|
|
197
|
+
return (
|
|
198
|
+
resolve_safe_child(root, f"{key}.bin"),
|
|
199
|
+
resolve_safe_child(root, f"{key}.json"),
|
|
200
|
+
resolve_safe_child(root, f"{key}.lock"),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _read_cached_file(bin_path: Path, meta_path: Path, ttl_hours: float) -> bytes | None:
|
|
205
|
+
if ttl_hours <= 0 or not bin_path.is_file():
|
|
206
|
+
return None
|
|
207
|
+
try:
|
|
208
|
+
entry = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
209
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
210
|
+
return None
|
|
211
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
212
|
+
return None
|
|
213
|
+
fetched = entry.get("fetched_at")
|
|
214
|
+
nbytes = entry.get("nbytes")
|
|
215
|
+
if not isinstance(fetched, (int, float)) or not isinstance(nbytes, int):
|
|
216
|
+
return None
|
|
217
|
+
if (time.time() - fetched) > ttl_hours * 3600:
|
|
218
|
+
return None
|
|
219
|
+
try:
|
|
220
|
+
data = bin_path.read_bytes()
|
|
221
|
+
except OSError:
|
|
222
|
+
return None
|
|
223
|
+
if len(data) != nbytes or nbytes <= 0:
|
|
224
|
+
return None
|
|
225
|
+
return data
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _download_bytes(url: str, *, timeout: float) -> bytes:
|
|
229
|
+
parsed = urlparse(url)
|
|
230
|
+
if parsed.scheme != "https" or not parsed.netloc:
|
|
231
|
+
raise click.ClickException(f"Refusing to download non-HTTPS URL: {url}")
|
|
232
|
+
try:
|
|
233
|
+
with httpx.Client(headers=DOWNLOAD_HEADERS, timeout=timeout, follow_redirects=True) as client:
|
|
234
|
+
resp = client.get(url)
|
|
235
|
+
resp.raise_for_status()
|
|
236
|
+
except httpx.HTTPError as exc:
|
|
237
|
+
raise click.ClickException(f"Failed downloading {url}: {exc}") from exc
|
|
238
|
+
if not resp.content:
|
|
239
|
+
raise click.ClickException(f"Download was empty: {url}")
|
|
240
|
+
return resp.content
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def cached_download_bytes(
|
|
244
|
+
url: str,
|
|
245
|
+
*,
|
|
246
|
+
timeout: float,
|
|
247
|
+
refresh: bool,
|
|
248
|
+
ttl_hours: float,
|
|
249
|
+
) -> tuple[bytes, bool]:
|
|
250
|
+
"""Return (bytes, cache_hit). A hit copies from disk and makes no HTTP request."""
|
|
251
|
+
bin_path, meta_path, lock_path = _file_cache_paths(url)
|
|
252
|
+
if not refresh:
|
|
253
|
+
hit = _read_cached_file(bin_path, meta_path, ttl_hours)
|
|
254
|
+
if hit is not None:
|
|
255
|
+
return hit, True
|
|
256
|
+
with file_lock(lock_path):
|
|
257
|
+
if not refresh:
|
|
258
|
+
hit = _read_cached_file(bin_path, meta_path, ttl_hours)
|
|
259
|
+
if hit is not None:
|
|
260
|
+
return hit, True
|
|
261
|
+
data = _download_bytes(url, timeout=timeout)
|
|
262
|
+
atomic_write_bytes(bin_path, data)
|
|
263
|
+
atomic_write_json(
|
|
264
|
+
meta_path,
|
|
265
|
+
{"schema": CACHE_SCHEMA, "fetched_at": time.time(), "url": url, "nbytes": len(data)},
|
|
266
|
+
)
|
|
267
|
+
return data, False
|
|
268
|
+
|
|
269
|
+
|
|
154
270
|
def cached_get_json(
|
|
155
271
|
url: str,
|
|
156
272
|
params: list[tuple[str, str]] | None,
|
|
@@ -505,13 +621,15 @@ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text, time
|
|
|
505
621
|
if not lccn or not date:
|
|
506
622
|
raise click.UsageError("Give a resource URL or both --lccn and --date.")
|
|
507
623
|
resource_url = _build_resource_url(lccn, date, edition, seq)
|
|
624
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
508
625
|
data, _hit = cached_get_json(_resource_url_json(resource_url), None, timeout=timeout,
|
|
509
|
-
refresh=refresh, ttl_hours=
|
|
626
|
+
refresh=refresh, ttl_hours=ttl)
|
|
510
627
|
item = data.get("item") or {}
|
|
511
628
|
outdir = Path(out)
|
|
512
629
|
outdir.mkdir(parents=True, exist_ok=True)
|
|
513
|
-
stem =
|
|
514
|
-
|
|
630
|
+
stem = safe_output_filename(
|
|
631
|
+
f"{_first(item.get('number_lccn')) or 'loc'}_{item.get('date') or 'nodate'}_sp{seq}"
|
|
632
|
+
)
|
|
515
633
|
resources = (data.get("resources") or [{}])[0]
|
|
516
634
|
jobs = []
|
|
517
635
|
if pdf and resources.get("pdf"):
|
|
@@ -523,19 +641,24 @@ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text, time
|
|
|
523
641
|
if not jobs:
|
|
524
642
|
click.echo("No downloadable resources found for this page.", err=True)
|
|
525
643
|
sys.exit(1)
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
(
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
644
|
+
for kind, url, filename in jobs:
|
|
645
|
+
safe_name = safe_output_filename(filename)
|
|
646
|
+
dest = resolve_safe_child(outdir, safe_name)
|
|
647
|
+
body, file_hit = cached_download_bytes(url, timeout=timeout, refresh=refresh, ttl_hours=ttl)
|
|
648
|
+
atomic_write_bytes(dest, body)
|
|
649
|
+
marker = " [cache]" if file_hit else ""
|
|
650
|
+
click.echo(f"{kind}: {dest} ({len(body)} bytes){marker}")
|
|
651
|
+
meta_name = safe_output_filename(f"{stem}.metadata.json")
|
|
652
|
+
meta_path = resolve_safe_child(outdir, meta_name)
|
|
653
|
+
atomic_write_bytes(
|
|
654
|
+
meta_path,
|
|
655
|
+
json.dumps(
|
|
656
|
+
{"resource_url": resource_url, "item": item, "resources": data.get("resources")},
|
|
657
|
+
indent=2,
|
|
658
|
+
ensure_ascii=False,
|
|
659
|
+
).encode("utf-8"),
|
|
660
|
+
)
|
|
661
|
+
click.echo(f"metadata: {meta_path}")
|
|
539
662
|
|
|
540
663
|
|
|
541
664
|
@cli.command()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: nara-catalog-search
|
|
3
|
-
description: Search, inspect, and download records from the National Archives Catalog via the bundled uv-based `nara` CLI, website advanced search, or v2 API. Covers CLI usage, query-string syntax, q operators, fielded parameters, filters, date and Congress ranges, pagination, and worked examples. Use when querying NARA, inspecting NAIDs, downloading digitized archival scans, or verifying genealogy records.
|
|
3
|
+
description: Search, inspect, and download records from the National Archives Catalog via the bundled uv-based `nara` CLI, website advanced search, or v2 API. Also searches the public 1950 Census population schedules. Covers CLI usage, query-string syntax, q operators, fielded parameters, filters, date and Congress ranges, pagination, and worked examples. Use when querying NARA, inspecting NAIDs, downloading digitized archival scans, searching the 1950 Census, or verifying genealogy records.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# NARA Catalog Search
|
|
@@ -17,13 +17,14 @@ Path: `skills/nara-catalog-search/scripts/nara`
|
|
|
17
17
|
|
|
18
18
|
### Persistent local disk cache
|
|
19
19
|
|
|
20
|
-
`search`, `get`, and `
|
|
20
|
+
`search`, `get`, `download`, and `census1950` cache responses atomically under `~/.cache/kinloom-nara/` (overrideable via `KINLOOM_NARA_CACHE_DIR`) using advisory file locks (`fcntl.flock` on POSIX, safe fallback elsewhere) so concurrent research threads never duplicate downloads and repeat calls make zero HTTP requests. Pass `--refresh` on `search`, `get`, `download`, or `census1950` to bypass the cache and fetch fresh data.
|
|
21
21
|
|
|
22
22
|
Cache layout:
|
|
23
23
|
|
|
24
24
|
- `records/<naid>.json`: full record metadata and digital object inventory shared by `get` and `download` (upgraded automatically if `--text` is requested later).
|
|
25
25
|
- `objects/<naid>/<page>_<safe_filename>`: individual downloaded page scans, so overlapping page slices (for example `--pages 315-350` followed by `--pages 340-360` or another biographer working the same census roll) reuse already-fetched pages straight from disk.
|
|
26
26
|
- `_queries/<sha256>.json`: cached `search` query payloads keyed by canonical query parameters with a 168-hour (7-day) default TTL (`--cache-ttl-hours` or `KINLOOM_NARA_QUERY_TTL_HOURS`).
|
|
27
|
+
- `census1950/<sha256>.json`: cached `census1950` responses, same TTL and the same `--cache-ttl-hours` / `KINLOOM_NARA_QUERY_TTL_HOURS` knobs. `0` skips cached reads.
|
|
27
28
|
|
|
28
29
|
### Search records (single or batched in one browser session)
|
|
29
30
|
|
|
@@ -63,6 +64,23 @@ skills/nara-catalog-search/scripts/nara download <naid> --pages 1-5 --out ./down
|
|
|
63
64
|
skills/nara-catalog-search/scripts/nara download <naid> --out ./downloads/nara-<naid>
|
|
64
65
|
```
|
|
65
66
|
|
|
67
|
+
### Search the 1950 Census population schedules
|
|
68
|
+
|
|
69
|
+
`census1950` calls the public JSON API on `https://1950census.archives.gov/api/search`. Measured 2026-11-25, `GET /api/search` returns JSON (`total`, `page`, `size`, `results`) and `GET /api/state` returns `{abbr, name}` rows. That host is not the Catalog v2 API. The command sends the same query names the public site uses: `state` (postal code), `county`, `name`, `ed`, `size` (from `--limit`), and `page=1`.
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
# Surname in one state. Repeat the same command and the second run does not call the network.
|
|
73
|
+
skills/nara-catalog-search/scripts/nara census1950 --state IL --name Lincoln --json
|
|
74
|
+
|
|
75
|
+
# One enumeration district
|
|
76
|
+
skills/nara-catalog-search/scripts/nara census1950 --state Illinois --county Sangamon --ed 84-1
|
|
77
|
+
|
|
78
|
+
# Force a new request
|
|
79
|
+
skills/nara-catalog-search/scripts/nara census1950 --state IL --name Lincoln --refresh
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Give at least one of `--state`, `--county`, `--name`, or `--ed`. `--limit` is 1 through 100 (default 25). `--json` adds `"cache_hit": true` or `false`. State names and the codes published by `GET /api/state` both work, including territories such as `PR` and `PC` (Panama Canal Zone).
|
|
83
|
+
|
|
66
84
|
### Build verified search URLs offline
|
|
67
85
|
|
|
68
86
|
```bash
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
Uses the official NARA Catalog v2 API when NARA_API_KEY is set, and falls back
|
|
13
13
|
to headless Chromium against catalog.archives.gov when no key is configured.
|
|
14
|
+
`census1950` calls the public 1950 Census site API at 1950census.archives.gov.
|
|
14
15
|
"""
|
|
15
16
|
|
|
16
17
|
from __future__ import annotations
|
|
@@ -1379,6 +1380,300 @@ def cmd_download(
|
|
|
1379
1380
|
click.echo(f"Done: {len(downloaded_manifest)} file(s) in {target_dir}")
|
|
1380
1381
|
|
|
1381
1382
|
|
|
1383
|
+
# Public 1950 Census population-schedule search (1950census.archives.gov/api).
|
|
1384
|
+
# Measured 2026-11-25: GET /api/search returns JSON. This host is not Catalog v2.
|
|
1385
|
+
CENSUS1950_API_BASE = "https://1950census.archives.gov/api"
|
|
1386
|
+
CENSUS1950_DEFAULT_LIMIT = 25
|
|
1387
|
+
CENSUS1950_STATES = {
|
|
1388
|
+
"AL": "Alabama",
|
|
1389
|
+
"AK": "Alaska",
|
|
1390
|
+
"AS": "American Samoa",
|
|
1391
|
+
"AZ": "Arizona",
|
|
1392
|
+
"AR": "Arkansas",
|
|
1393
|
+
"CA": "California",
|
|
1394
|
+
"CN": "Canton Island",
|
|
1395
|
+
"CO": "Colorado",
|
|
1396
|
+
"CT": "Connecticut",
|
|
1397
|
+
"DE": "Delaware",
|
|
1398
|
+
"DC": "District of Columbia",
|
|
1399
|
+
"FL": "Florida",
|
|
1400
|
+
"GA": "Georgia",
|
|
1401
|
+
"GU": "Guam",
|
|
1402
|
+
"HI": "Hawaii",
|
|
1403
|
+
"ID": "Idaho",
|
|
1404
|
+
"IL": "Illinois",
|
|
1405
|
+
"IN": "Indiana",
|
|
1406
|
+
"IA": "Iowa",
|
|
1407
|
+
"JN": "Johnston Island",
|
|
1408
|
+
"KS": "Kansas",
|
|
1409
|
+
"KY": "Kentucky",
|
|
1410
|
+
"LA": "Louisiana",
|
|
1411
|
+
"ME": "Maine",
|
|
1412
|
+
"MD": "Maryland",
|
|
1413
|
+
"MA": "Massachusetts",
|
|
1414
|
+
"MI": "Michigan",
|
|
1415
|
+
"MW": "Midway Island",
|
|
1416
|
+
"MN": "Minnesota",
|
|
1417
|
+
"MS": "Mississippi",
|
|
1418
|
+
"MO": "Missouri",
|
|
1419
|
+
"MT": "Montana",
|
|
1420
|
+
"NE": "Nebraska",
|
|
1421
|
+
"NV": "Nevada",
|
|
1422
|
+
"NH": "New Hampshire",
|
|
1423
|
+
"NJ": "New Jersey",
|
|
1424
|
+
"NM": "New Mexico",
|
|
1425
|
+
"NY": "New York",
|
|
1426
|
+
"NC": "North Carolina",
|
|
1427
|
+
"ND": "North Dakota",
|
|
1428
|
+
"OH": "Ohio",
|
|
1429
|
+
"OK": "Oklahoma",
|
|
1430
|
+
"OR": "Oregon",
|
|
1431
|
+
"OI": "Overseas Island Possessions",
|
|
1432
|
+
"PC": "Panama Canal Zone",
|
|
1433
|
+
"PA": "Pennsylvania",
|
|
1434
|
+
"PR": "Puerto Rico",
|
|
1435
|
+
"RI": "Rhode Island",
|
|
1436
|
+
"SC": "South Carolina",
|
|
1437
|
+
"SD": "South Dakota",
|
|
1438
|
+
"TN": "Tennessee",
|
|
1439
|
+
"TX": "Texas",
|
|
1440
|
+
"UT": "Utah",
|
|
1441
|
+
"VT": "Vermont",
|
|
1442
|
+
"VI": "Virgin Islands",
|
|
1443
|
+
"VA": "Virginia",
|
|
1444
|
+
"WK": "Wake Island",
|
|
1445
|
+
"WA": "Washington",
|
|
1446
|
+
"WV": "West Virginia",
|
|
1447
|
+
"WI": "Wisconsin",
|
|
1448
|
+
"WY": "Wyoming",
|
|
1449
|
+
}
|
|
1450
|
+
_CENSUS1950_STATE_BY_NAME = {name.casefold(): abbr for abbr, name in CENSUS1950_STATES.items()}
|
|
1451
|
+
|
|
1452
|
+
|
|
1453
|
+
def normalize_census1950_state(raw: str) -> str:
|
|
1454
|
+
text = raw.strip()
|
|
1455
|
+
if not text or "\x00" in text:
|
|
1456
|
+
raise click.BadParameter(f"Invalid --state value: {raw!r}")
|
|
1457
|
+
upper = text.upper()
|
|
1458
|
+
if upper in CENSUS1950_STATES:
|
|
1459
|
+
return upper
|
|
1460
|
+
found = _CENSUS1950_STATE_BY_NAME.get(text.casefold())
|
|
1461
|
+
if found:
|
|
1462
|
+
return found
|
|
1463
|
+
raise click.BadParameter(
|
|
1464
|
+
f"Unknown 1950 Census state: {raw!r}. Use a code such as IL or a name such as Illinois."
|
|
1465
|
+
)
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
def _census1950_plain_token(raw: str, flag: str, *, max_len: int) -> str:
|
|
1469
|
+
text = raw.strip()
|
|
1470
|
+
if (
|
|
1471
|
+
not text
|
|
1472
|
+
or len(text) > max_len
|
|
1473
|
+
or "\x00" in text
|
|
1474
|
+
or re.search(r"[\x00-\x1f\\/]|\.\.", text)
|
|
1475
|
+
):
|
|
1476
|
+
raise click.BadParameter(f"Invalid {flag} value: {raw!r}")
|
|
1477
|
+
return text
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def canonical_census1950_query(
|
|
1481
|
+
*,
|
|
1482
|
+
state: str | None,
|
|
1483
|
+
county: str | None,
|
|
1484
|
+
name: str | None,
|
|
1485
|
+
ed: str | None,
|
|
1486
|
+
limit: int,
|
|
1487
|
+
) -> dict[str, Any]:
|
|
1488
|
+
"""One search the 1950 Census site can run. Empty filters stay empty strings."""
|
|
1489
|
+
if limit < 1 or limit > 100:
|
|
1490
|
+
raise click.BadParameter(f"Invalid --limit value: {limit!r} (must be 1..100).")
|
|
1491
|
+
state_code = normalize_census1950_state(state) if state and state.strip() else ""
|
|
1492
|
+
county_text = _census1950_plain_token(county, "--county", max_len=80) if county and county.strip() else ""
|
|
1493
|
+
name_text = _census1950_plain_token(name, "--name", max_len=120) if name and name.strip() else ""
|
|
1494
|
+
ed_text = ""
|
|
1495
|
+
if ed and ed.strip():
|
|
1496
|
+
ed_text = _census1950_plain_token(ed, "--ed", max_len=32)
|
|
1497
|
+
if not re.fullmatch(r"[0-9A-Za-z]+(?:-[0-9A-Za-z]+)*", ed_text):
|
|
1498
|
+
raise click.BadParameter(f"Invalid --ed value: {ed!r}")
|
|
1499
|
+
if not any((state_code, county_text, name_text, ed_text)):
|
|
1500
|
+
raise click.UsageError("Give at least one of --state, --county, --name, or --ed.")
|
|
1501
|
+
return {
|
|
1502
|
+
"state": state_code,
|
|
1503
|
+
"county": county_text,
|
|
1504
|
+
"name": name_text,
|
|
1505
|
+
"ed": ed_text,
|
|
1506
|
+
"limit": int(limit),
|
|
1507
|
+
"page": 1,
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
|
|
1511
|
+
def census1950_search_url(canonical: dict[str, Any]) -> str:
|
|
1512
|
+
params = {
|
|
1513
|
+
"state": canonical["state"],
|
|
1514
|
+
"county": canonical["county"],
|
|
1515
|
+
"name": canonical["name"],
|
|
1516
|
+
"ed": canonical["ed"],
|
|
1517
|
+
"size": str(canonical["limit"]),
|
|
1518
|
+
"page": str(canonical["page"]),
|
|
1519
|
+
}
|
|
1520
|
+
query = urlencode({key: value for key, value in params.items() if value})
|
|
1521
|
+
return f"{CENSUS1950_API_BASE}/search?{query}"
|
|
1522
|
+
|
|
1523
|
+
|
|
1524
|
+
def census1950_cache_paths(canonical: dict[str, Any], cache_root: Path) -> tuple[Path, Path]:
|
|
1525
|
+
digest = hashlib.sha256(
|
|
1526
|
+
json.dumps(canonical, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
|
|
1527
|
+
"utf-8"
|
|
1528
|
+
)
|
|
1529
|
+
).hexdigest()
|
|
1530
|
+
directory = cache_root / "census1950"
|
|
1531
|
+
return (
|
|
1532
|
+
resolve_safe_child(directory, f"{digest}.json"),
|
|
1533
|
+
resolve_safe_child(directory, f"{digest}.lock"),
|
|
1534
|
+
)
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def _read_cached_census1950(
|
|
1538
|
+
path: Path, *, ttl_hours: float
|
|
1539
|
+
) -> dict[str, Any] | None:
|
|
1540
|
+
if ttl_hours <= 0:
|
|
1541
|
+
return None
|
|
1542
|
+
envelope = read_json_if_valid(path)
|
|
1543
|
+
if envelope is None:
|
|
1544
|
+
return None
|
|
1545
|
+
cached_at = envelope.get("cached_at")
|
|
1546
|
+
data = envelope.get("data")
|
|
1547
|
+
if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
|
|
1548
|
+
return None
|
|
1549
|
+
if not isinstance(data.get("results"), list):
|
|
1550
|
+
return None
|
|
1551
|
+
if (time.time() - float(cached_at)) <= ttl_hours * 3600.0:
|
|
1552
|
+
return data
|
|
1553
|
+
return None
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
def _census1950_fetch_json(url: str) -> dict[str, Any]:
|
|
1557
|
+
headers = {
|
|
1558
|
+
"Accept": "application/json",
|
|
1559
|
+
"User-Agent": "kinloom/1.0 (genealogy research)",
|
|
1560
|
+
}
|
|
1561
|
+
with httpx.Client(timeout=30.0, follow_redirects=True) as client:
|
|
1562
|
+
resp = client.get(url, headers=headers)
|
|
1563
|
+
resp.raise_for_status()
|
|
1564
|
+
content_type = resp.headers.get("content-type", "")
|
|
1565
|
+
if "json" not in content_type.lower():
|
|
1566
|
+
raise click.ClickException(
|
|
1567
|
+
f"1950 Census API did not return JSON ({content_type or 'no content type'})."
|
|
1568
|
+
)
|
|
1569
|
+
try:
|
|
1570
|
+
data = resp.json()
|
|
1571
|
+
except ValueError as exc:
|
|
1572
|
+
raise click.ClickException("1950 Census API returned invalid JSON.") from exc
|
|
1573
|
+
if not isinstance(data, dict) or not isinstance(data.get("results"), list):
|
|
1574
|
+
raise click.ClickException("1950 Census API returned an unexpected payload.")
|
|
1575
|
+
return data
|
|
1576
|
+
|
|
1577
|
+
|
|
1578
|
+
def _emit_census1950(data: dict[str, Any], *, cache_hit: bool, as_json: bool) -> None:
|
|
1579
|
+
if as_json:
|
|
1580
|
+
payload = {
|
|
1581
|
+
"cache_hit": cache_hit,
|
|
1582
|
+
"total": data.get("total"),
|
|
1583
|
+
"page": data.get("page"),
|
|
1584
|
+
"size": data.get("size"),
|
|
1585
|
+
"results": data.get("results") or [],
|
|
1586
|
+
}
|
|
1587
|
+
click.echo(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
1588
|
+
return
|
|
1589
|
+
total = data.get("total")
|
|
1590
|
+
header = f"1950 Census population schedules: {total} hit(s)"
|
|
1591
|
+
if cache_hit:
|
|
1592
|
+
header += " [cache]"
|
|
1593
|
+
lines = [header]
|
|
1594
|
+
for row in data.get("results") or []:
|
|
1595
|
+
if not isinstance(row, dict):
|
|
1596
|
+
continue
|
|
1597
|
+
lines.append(
|
|
1598
|
+
" ".join(
|
|
1599
|
+
part
|
|
1600
|
+
for part in (
|
|
1601
|
+
str(row.get("abbr") or row.get("state") or ""),
|
|
1602
|
+
str(row.get("county") or ""),
|
|
1603
|
+
f"ED {row.get('ed')}" if row.get("ed") else "",
|
|
1604
|
+
f"schedule {row.get('scheduleId')}" if row.get("scheduleId") else "",
|
|
1605
|
+
)
|
|
1606
|
+
if part
|
|
1607
|
+
)
|
|
1608
|
+
)
|
|
1609
|
+
for person in row.get("names") or []:
|
|
1610
|
+
if isinstance(person, dict) and person.get("name"):
|
|
1611
|
+
row_no = person.get("row")
|
|
1612
|
+
prefix = f"{row_no}: " if row_no else ""
|
|
1613
|
+
lines.append(f" {prefix}{person['name']}")
|
|
1614
|
+
click.echo("\n".join(lines))
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
@cli.command("census1950")
|
|
1618
|
+
@click.option("--state", default=None, help="State or territory code (IL) or name (Illinois).")
|
|
1619
|
+
@click.option("--county", default=None, help="County name, as the 1950 Census site spells it.")
|
|
1620
|
+
@click.option("--name", default=None, help="Person name. Sent as the site name= parameter.")
|
|
1621
|
+
@click.option("--ed", default=None, help="Enumeration district, for example 49-16.")
|
|
1622
|
+
@click.option(
|
|
1623
|
+
"--limit",
|
|
1624
|
+
default=CENSUS1950_DEFAULT_LIMIT,
|
|
1625
|
+
show_default=True,
|
|
1626
|
+
type=int,
|
|
1627
|
+
help="Results per page (API size=, 1..100).",
|
|
1628
|
+
)
|
|
1629
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of text.")
|
|
1630
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache and query the 1950 Census API.")
|
|
1631
|
+
@click.option(
|
|
1632
|
+
"--cache-ttl-hours",
|
|
1633
|
+
default=None,
|
|
1634
|
+
type=float,
|
|
1635
|
+
help=f"Cache TTL in hours (default {DEFAULT_QUERY_TTL_HOURS:g}; env KINLOOM_NARA_QUERY_TTL_HOURS).",
|
|
1636
|
+
)
|
|
1637
|
+
def cmd_census1950(
|
|
1638
|
+
state: str | None,
|
|
1639
|
+
county: str | None,
|
|
1640
|
+
name: str | None,
|
|
1641
|
+
ed: str | None,
|
|
1642
|
+
limit: int,
|
|
1643
|
+
as_json: bool,
|
|
1644
|
+
refresh: bool,
|
|
1645
|
+
cache_ttl_hours: float | None,
|
|
1646
|
+
) -> None:
|
|
1647
|
+
"""Search 1950 Census population schedules on 1950census.archives.gov.
|
|
1648
|
+
|
|
1649
|
+
Results are cached under ~/.cache/kinloom-nara/census1950/ (168 h TTL).
|
|
1650
|
+
A repeat call with the same filters makes no HTTP request.
|
|
1651
|
+
"""
|
|
1652
|
+
canonical = canonical_census1950_query(
|
|
1653
|
+
state=state, county=county, name=name, ed=ed, limit=limit
|
|
1654
|
+
)
|
|
1655
|
+
ttl_hours = resolve_query_ttl_hours(cache_ttl_hours)
|
|
1656
|
+
cache_root = get_cache_root()
|
|
1657
|
+
data_path, lock_path = census1950_cache_paths(canonical, cache_root)
|
|
1658
|
+
if not refresh:
|
|
1659
|
+
cached = _read_cached_census1950(data_path, ttl_hours=ttl_hours)
|
|
1660
|
+
if cached is not None:
|
|
1661
|
+
_emit_census1950(cached, cache_hit=True, as_json=as_json)
|
|
1662
|
+
return
|
|
1663
|
+
with file_lock(lock_path):
|
|
1664
|
+
if not refresh:
|
|
1665
|
+
cached = _read_cached_census1950(data_path, ttl_hours=ttl_hours)
|
|
1666
|
+
if cached is not None:
|
|
1667
|
+
_emit_census1950(cached, cache_hit=True, as_json=as_json)
|
|
1668
|
+
return
|
|
1669
|
+
fetched = _census1950_fetch_json(census1950_search_url(canonical))
|
|
1670
|
+
atomic_write_json(
|
|
1671
|
+
data_path,
|
|
1672
|
+
{"cached_at": time.time(), "params": canonical, "data": fetched},
|
|
1673
|
+
)
|
|
1674
|
+
_emit_census1950(fetched, cache_hit=False, as_json=as_json)
|
|
1675
|
+
|
|
1676
|
+
|
|
1382
1677
|
if __name__ == "__main__":
|
|
1383
1678
|
try:
|
|
1384
1679
|
cli()
|
package/dist/client.js
CHANGED
|
@@ -153,7 +153,7 @@ export class KinloomApiClient {
|
|
|
153
153
|
this.baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
154
154
|
this.token = options.token?.trim() || undefined;
|
|
155
155
|
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
156
|
-
this.userAgent = options.userAgent ?? 'kinloom-cli/0.
|
|
156
|
+
this.userAgent = options.userAgent ?? 'kinloom-cli/0.4.0';
|
|
157
157
|
}
|
|
158
158
|
buildHeaders(extra) {
|
|
159
159
|
const headers = new Headers();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kinloom/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Operator and AI research agent CLI for initializing, slicing GEDCOM, seeding, submitting batches, and exporting Kinloom archives.",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@kinloom/core": "^0.
|
|
35
|
+
"@kinloom/core": "^0.4.0",
|
|
36
36
|
"yaml": "^2.9.1",
|
|
37
37
|
"zod": "^4.6.7"
|
|
38
38
|
}
|