@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.
- package/dist/assets/cached-ocr.py +346 -116
- package/dist/assets/ocr.md +25 -1
- package/dist/assets/prep-scan.md +42 -4
- package/dist/assets/prep-scan.py +432 -10
- package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
- package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
- package/dist/bundled-skills/archive-org/SKILL.md +40 -7
- package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
- package/dist/bundled-skills/california-archives/SKILL.md +10 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
- package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
- package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
- package/dist/bundled-skills/findagrave/SKILL.md +18 -5
- package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
- package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
- package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
- package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
- package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
- package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
- package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
- package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
- package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
- package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
- package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
- package/dist/bundled-skills/wikitree/SKILL.md +7 -1
- package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +107 -2
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts.map +1 -1
- package/dist/commands/ops/audit.js +5 -0
- package/dist/commands/ops/audit.js.map +1 -1
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +3 -1
- package/dist/commands/ops/help.d.ts.map +1 -1
- package/dist/commands/ops/help.js +33 -0
- package/dist/commands/ops/help.js.map +1 -1
- package/dist/commands/ops/index.d.ts +3 -1
- package/dist/commands/ops/index.d.ts.map +1 -1
- package/dist/commands/ops/index.js +2 -0
- package/dist/commands/ops/index.js.map +1 -1
- package/dist/commands/ops/integrate.d.ts +5 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -1
- package/dist/commands/ops/integrate.js +217 -26
- package/dist/commands/ops/integrate.js.map +1 -1
- package/dist/commands/ops/sync.d.ts +17 -0
- package/dist/commands/ops/sync.d.ts.map +1 -1
- package/dist/commands/ops/sync.js +173 -0
- package/dist/commands/ops/sync.js.map +1 -1
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/index.d.ts +1 -1
- package/dist/commands/records/index.d.ts.map +1 -1
- package/dist/commands/records/index.js +1 -1
- package/dist/commands/records/index.js.map +1 -1
- package/dist/commands/records/runner.d.ts +2 -0
- package/dist/commands/records/runner.d.ts.map +1 -1
- package/dist/commands/records/runner.js +33 -2
- package/dist/commands/records/runner.js.map +1 -1
- package/package.json +2 -2
|
@@ -64,8 +64,14 @@ skills/wikitree/scripts/wikitree bio <WikiTree-ID>
|
|
|
64
64
|
skills/wikitree/scripts/wikitree bio <WikiTree-ID> --format html
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
-
###
|
|
67
|
+
### Disk cache and environment variables
|
|
68
68
|
|
|
69
|
+
`search`, `person`, `ancestors`, and `bio` cache successful API responses on disk under `~/.cache/kinloom-wikitree/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors and non-zero WikiTree API status errors are never cached.
|
|
70
|
+
|
|
71
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
72
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
73
|
+
- `KINLOOM_WIKITREE_CACHE_DIR`: override the cache directory path.
|
|
74
|
+
- `KINLOOM_WIKITREE_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
69
75
|
- `WIKITREE_APP_ID`: application id sent with every API call (default
|
|
70
76
|
`Kinloom`). WikiTree asks every client to send one; calls without an id
|
|
71
77
|
are subject to strict rate limits.
|
|
@@ -15,28 +15,171 @@ skills/wikitree/SKILL.md for the API reference and rules.
|
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
|
+
import hashlib
|
|
18
19
|
import json
|
|
20
|
+
import math
|
|
19
21
|
import os
|
|
20
22
|
import sys
|
|
23
|
+
import time
|
|
24
|
+
from contextlib import contextmanager
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Callable, Iterator
|
|
21
27
|
|
|
22
28
|
import click
|
|
23
29
|
import httpx
|
|
24
30
|
|
|
31
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
32
|
+
CACHE_SCHEMA = 1
|
|
33
|
+
|
|
25
34
|
API_BASE = "https://api.wikitree.com/api.php"
|
|
26
35
|
DEFAULT_APP_ID = "Kinloom"
|
|
27
36
|
DEFAULT_FIELDS = "Id,Name,FirstName,LastNameAtBirth,BirthDate,DeathDate,BirthLocation"
|
|
28
37
|
|
|
29
38
|
|
|
39
|
+
def cache_dir() -> Path:
|
|
40
|
+
override = os.environ.get("KINLOOM_WIKITREE_CACHE_DIR")
|
|
41
|
+
if override:
|
|
42
|
+
return Path(override).expanduser()
|
|
43
|
+
return Path.home() / ".cache" / "kinloom-wikitree"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
47
|
+
if cli_ttl is not None:
|
|
48
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
49
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
50
|
+
return float(cli_ttl)
|
|
51
|
+
raw = os.environ.get("KINLOOM_WIKITREE_CACHE_TTL_HOURS")
|
|
52
|
+
if raw is not None and raw.strip():
|
|
53
|
+
try:
|
|
54
|
+
parsed = float(raw.strip())
|
|
55
|
+
except ValueError as exc:
|
|
56
|
+
raise click.BadParameter(f"Invalid KINLOOM_WIKITREE_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
57
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
58
|
+
raise click.BadParameter(
|
|
59
|
+
f"Invalid KINLOOM_WIKITREE_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
60
|
+
)
|
|
61
|
+
return parsed
|
|
62
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@contextmanager
|
|
66
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
67
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
68
|
+
try:
|
|
69
|
+
import fcntl
|
|
70
|
+
except ImportError:
|
|
71
|
+
yield
|
|
72
|
+
return
|
|
73
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
with open(lock_path, "a+b") as lock_file:
|
|
75
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
76
|
+
try:
|
|
77
|
+
yield
|
|
78
|
+
finally:
|
|
79
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
83
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
85
|
+
try:
|
|
86
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
87
|
+
os.replace(tmp, dest)
|
|
88
|
+
except Exception:
|
|
89
|
+
tmp.unlink(missing_ok=True)
|
|
90
|
+
raise
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
94
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
95
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
99
|
+
if not path.is_file():
|
|
100
|
+
return None
|
|
101
|
+
try:
|
|
102
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
103
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
104
|
+
return None
|
|
105
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
106
|
+
return None
|
|
107
|
+
fetched = entry.get("fetched_at")
|
|
108
|
+
if not isinstance(fetched, (int, float)):
|
|
109
|
+
return None
|
|
110
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
111
|
+
return None
|
|
112
|
+
result = entry.get("result")
|
|
113
|
+
return result if isinstance(result, dict) else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cached_call(
|
|
117
|
+
kind: str,
|
|
118
|
+
payload: dict,
|
|
119
|
+
fetch: Callable[[], dict],
|
|
120
|
+
*,
|
|
121
|
+
refresh: bool,
|
|
122
|
+
ttl_hours: float,
|
|
123
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
124
|
+
) -> tuple[dict, bool]:
|
|
125
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
126
|
+
key = cache_key(kind, payload)
|
|
127
|
+
root = cache_dir()
|
|
128
|
+
path = root / f"{key}.json"
|
|
129
|
+
if not refresh:
|
|
130
|
+
hit = read_cache(path, ttl_hours)
|
|
131
|
+
if hit is not None:
|
|
132
|
+
return hit, True
|
|
133
|
+
with file_lock(root / f"{key}.lock"):
|
|
134
|
+
if not refresh:
|
|
135
|
+
hit = read_cache(path, ttl_hours)
|
|
136
|
+
if hit is not None:
|
|
137
|
+
return hit, True
|
|
138
|
+
result = fetch()
|
|
139
|
+
if cacheable(result):
|
|
140
|
+
atomic_write_json(
|
|
141
|
+
path,
|
|
142
|
+
{
|
|
143
|
+
"schema": CACHE_SCHEMA,
|
|
144
|
+
"fetched_at": time.time(),
|
|
145
|
+
"kind": kind,
|
|
146
|
+
"query": payload,
|
|
147
|
+
"result": result,
|
|
148
|
+
},
|
|
149
|
+
)
|
|
150
|
+
return result, False
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def cache_options(func: Callable) -> Callable:
|
|
154
|
+
func = click.option(
|
|
155
|
+
"--cache-ttl-hours",
|
|
156
|
+
type=float,
|
|
157
|
+
default=None,
|
|
158
|
+
help="Cache TTL in hours (default 168, env KINLOOM_WIKITREE_CACHE_TTL_HOURS; 0 disables reads).",
|
|
159
|
+
)(func)
|
|
160
|
+
func = click.option(
|
|
161
|
+
"--refresh",
|
|
162
|
+
is_flag=True,
|
|
163
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
164
|
+
)(func)
|
|
165
|
+
return func
|
|
166
|
+
|
|
167
|
+
|
|
30
168
|
def _app_id() -> str:
|
|
31
169
|
return os.environ.get("WIKITREE_APP_ID", DEFAULT_APP_ID)
|
|
32
170
|
|
|
33
171
|
|
|
172
|
+
def _client() -> httpx.Client:
|
|
173
|
+
return httpx.Client(timeout=30.0)
|
|
174
|
+
|
|
175
|
+
|
|
34
176
|
def api_call(params: dict) -> list:
|
|
35
177
|
"""One GET against the WikiTree API; returns the decoded JSON array."""
|
|
36
|
-
|
|
178
|
+
full_params = {"appId": _app_id(), **params}
|
|
37
179
|
try:
|
|
38
|
-
|
|
39
|
-
|
|
180
|
+
with _client() as client:
|
|
181
|
+
resp = client.get(API_BASE, params=full_params)
|
|
182
|
+
resp.raise_for_status()
|
|
40
183
|
except httpx.HTTPError as exc:
|
|
41
184
|
raise click.ClickException(f"WikiTree API request failed: {exc}") from exc
|
|
42
185
|
try:
|
|
@@ -48,6 +191,39 @@ def api_call(params: dict) -> list:
|
|
|
48
191
|
return data
|
|
49
192
|
|
|
50
193
|
|
|
194
|
+
def _cached_api(
|
|
195
|
+
kind: str,
|
|
196
|
+
params: dict,
|
|
197
|
+
label: str,
|
|
198
|
+
*,
|
|
199
|
+
refresh: bool,
|
|
200
|
+
ttl_hours: float,
|
|
201
|
+
cacheable: Callable[[list], bool] = lambda d: bool(d),
|
|
202
|
+
) -> tuple[list, dict, bool]:
|
|
203
|
+
def _fetch() -> dict:
|
|
204
|
+
data = api_call(params)
|
|
205
|
+
check_status(data, label)
|
|
206
|
+
return {"data": data}
|
|
207
|
+
|
|
208
|
+
wrapped, hit = cached_call(
|
|
209
|
+
kind,
|
|
210
|
+
params,
|
|
211
|
+
_fetch,
|
|
212
|
+
refresh=refresh,
|
|
213
|
+
ttl_hours=ttl_hours,
|
|
214
|
+
cacheable=lambda r: isinstance(r.get("data"), list) and cacheable(r["data"]),
|
|
215
|
+
)
|
|
216
|
+
data = wrapped["data"]
|
|
217
|
+
first = check_status(data, label)
|
|
218
|
+
return data, first, hit
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _json_with_cache_hit(data: list, hit: bool) -> list:
|
|
222
|
+
if data and isinstance(data[0], dict):
|
|
223
|
+
return [{**data[0], "cache_hit": hit}, *data[1:]]
|
|
224
|
+
return data
|
|
225
|
+
|
|
226
|
+
|
|
51
227
|
def check_status(data: list, label: str) -> dict:
|
|
52
228
|
"""Raise on a non-zero status element; return the first element."""
|
|
53
229
|
if not data:
|
|
@@ -99,8 +275,10 @@ def cli() -> None:
|
|
|
99
275
|
@click.option("--fields", default=DEFAULT_FIELDS, show_default=True,
|
|
100
276
|
help="Comma-separated profile fields, or '*'.")
|
|
101
277
|
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
278
|
+
@cache_options
|
|
102
279
|
def search(first_name, last_name, birth_date, death_date, birth_location,
|
|
103
|
-
death_location, date_include, limit, start, fields, as_json
|
|
280
|
+
death_location, date_include, limit, start, fields, as_json,
|
|
281
|
+
refresh, cache_ttl_hours):
|
|
104
282
|
"""Search person profiles, e.g. search --first Abraham --last Lincoln."""
|
|
105
283
|
if not any([first_name, last_name, birth_date, death_date,
|
|
106
284
|
birth_location, death_location]):
|
|
@@ -121,13 +299,23 @@ def search(first_name, last_name, birth_date, death_date, birth_location,
|
|
|
121
299
|
params["DeathLocation"] = death_location
|
|
122
300
|
if date_include:
|
|
123
301
|
params["dateInclude"] = date_include
|
|
124
|
-
|
|
125
|
-
first =
|
|
302
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
303
|
+
data, first, hit = _cached_api(
|
|
304
|
+
"search",
|
|
305
|
+
params,
|
|
306
|
+
"searchPerson",
|
|
307
|
+
refresh=refresh,
|
|
308
|
+
ttl_hours=ttl,
|
|
309
|
+
cacheable=lambda d: bool(d) and isinstance(d[0], dict) and (
|
|
310
|
+
isinstance(d[0].get("matches"), list) or isinstance(d[0].get("total"), int)
|
|
311
|
+
),
|
|
312
|
+
)
|
|
126
313
|
if as_json:
|
|
127
|
-
click.echo(json.dumps(data, indent=2))
|
|
314
|
+
click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
|
|
128
315
|
return
|
|
129
316
|
matches = first.get("matches", [])
|
|
130
|
-
|
|
317
|
+
marker = " [cache]" if hit else ""
|
|
318
|
+
click.echo(f"{first.get('total', len(matches))} match(es), showing {len(matches)}:{marker}")
|
|
131
319
|
for match in matches:
|
|
132
320
|
if "Name" in match or "FirstName" in match:
|
|
133
321
|
show_person(match)
|
|
@@ -145,7 +333,8 @@ def search(first_name, last_name, birth_date, death_date, birth_location,
|
|
|
145
333
|
@click.option("--resolve-redirect", is_flag=True,
|
|
146
334
|
help="Follow merged-profile redirects.")
|
|
147
335
|
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
148
|
-
|
|
336
|
+
@cache_options
|
|
337
|
+
def person(key, fields, bio_format, resolve_redirect, as_json, refresh, cache_ttl_hours):
|
|
149
338
|
"""Fetch one person by WikiTree ID (e.g. <Surname>-<Number>) or numeric Id."""
|
|
150
339
|
params: dict = {"action": "getPerson", "key": key, "fields": fields}
|
|
151
340
|
if bio_format:
|
|
@@ -154,15 +343,41 @@ def person(key, fields, bio_format, resolve_redirect, as_json):
|
|
|
154
343
|
params["fields"] = fields + ",Bio"
|
|
155
344
|
if resolve_redirect:
|
|
156
345
|
params["resolveRedirect"] = 1
|
|
157
|
-
|
|
158
|
-
first =
|
|
346
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
347
|
+
data, first, hit = _cached_api(
|
|
348
|
+
"person",
|
|
349
|
+
params,
|
|
350
|
+
f"getPerson {key}",
|
|
351
|
+
refresh=refresh,
|
|
352
|
+
ttl_hours=ttl,
|
|
353
|
+
cacheable=lambda d: bool(d) and isinstance(d[0], dict) and bool(
|
|
354
|
+
d[0].get("person") or d[0].get("profile")
|
|
355
|
+
),
|
|
356
|
+
)
|
|
159
357
|
if as_json:
|
|
160
|
-
click.echo(json.dumps(data, indent=2))
|
|
358
|
+
click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
|
|
161
359
|
return
|
|
162
360
|
profile = first.get("person") or first.get("profile")
|
|
163
361
|
if not profile:
|
|
164
362
|
raise click.ClickException(f"getPerson {key}: no profile returned")
|
|
165
|
-
|
|
363
|
+
if hit:
|
|
364
|
+
name = profile.get("Name") or profile.get("Id", "?")
|
|
365
|
+
first_n = profile.get("FirstName", "")
|
|
366
|
+
last = profile.get("LastNameAtBirth") or profile.get("LastNameCurrent", "")
|
|
367
|
+
birth = profile.get("BirthDate") or ""
|
|
368
|
+
death = profile.get("DeathDate") or ""
|
|
369
|
+
birth = "" if birth in ("", "0000-00-00") else birth
|
|
370
|
+
death = "" if death in ("", "0000-00-00") else death
|
|
371
|
+
place = profile.get("BirthLocation", "")
|
|
372
|
+
dates = f"b. {birth}" if birth else "b. ?"
|
|
373
|
+
if death:
|
|
374
|
+
dates += f" d. {death}"
|
|
375
|
+
line = f"{name}: {first_n} {last} ({dates})"
|
|
376
|
+
if place:
|
|
377
|
+
line += f", born {place}"
|
|
378
|
+
click.echo(f"{line.strip()} [cache]")
|
|
379
|
+
else:
|
|
380
|
+
show_person(profile)
|
|
166
381
|
if bio_format and profile.get("Bio"):
|
|
167
382
|
click.echo(profile["Bio"])
|
|
168
383
|
|
|
@@ -174,7 +389,8 @@ def person(key, fields, bio_format, resolve_redirect, as_json):
|
|
|
174
389
|
@click.option("--fields", default=DEFAULT_FIELDS, show_default=True,
|
|
175
390
|
help="Comma-separated profile fields, or '*'.")
|
|
176
391
|
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
177
|
-
|
|
392
|
+
@cache_options
|
|
393
|
+
def ancestors(key, depth, fields, as_json, refresh, cache_ttl_hours):
|
|
178
394
|
"""Fetch ancestors of KEY, following father and mother.
|
|
179
395
|
|
|
180
396
|
Uses getPeople with ancestors=N: the standalone getAncestors action
|
|
@@ -182,11 +398,18 @@ def ancestors(key, depth, fields, as_json):
|
|
|
182
398
|
getPeople instead). The people dict includes the subject profile
|
|
183
399
|
itself, so it is excluded from the listing.
|
|
184
400
|
"""
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
first =
|
|
401
|
+
params = {"action": "getPeople", "keys": key, "ancestors": depth, "fields": fields}
|
|
402
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
403
|
+
data, first, hit = _cached_api(
|
|
404
|
+
"ancestors",
|
|
405
|
+
params,
|
|
406
|
+
f"getPeople {key}",
|
|
407
|
+
refresh=refresh,
|
|
408
|
+
ttl_hours=ttl,
|
|
409
|
+
cacheable=lambda d: bool(d) and isinstance(d[0], dict) and isinstance(d[0].get("people"), dict),
|
|
410
|
+
)
|
|
188
411
|
if as_json:
|
|
189
|
-
click.echo(json.dumps(data, indent=2))
|
|
412
|
+
click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
|
|
190
413
|
return
|
|
191
414
|
people = first.get("people", {})
|
|
192
415
|
subject = (first.get("resultByKey") or {}).get(key, {})
|
|
@@ -194,7 +417,8 @@ def ancestors(key, depth, fields, as_json):
|
|
|
194
417
|
profiles = [p for pid, p in people.items() if pid != subject_id]
|
|
195
418
|
profiles.sort(key=lambda p: (p.get("BirthDate") or "9999",
|
|
196
419
|
p.get("Name") or ""))
|
|
197
|
-
|
|
420
|
+
marker = " [cache]" if hit else ""
|
|
421
|
+
click.echo(f"{len(profiles)} ancestor(s) within {depth} generation(s) of {key}:{marker}")
|
|
198
422
|
for profile in profiles:
|
|
199
423
|
show_person(profile)
|
|
200
424
|
|
|
@@ -204,15 +428,27 @@ def ancestors(key, depth, fields, as_json):
|
|
|
204
428
|
@click.option("--format", "bio_format", type=click.Choice(["wiki", "html", "both"]),
|
|
205
429
|
default="wiki", show_default=True, help="Biography format.")
|
|
206
430
|
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
207
|
-
|
|
431
|
+
@cache_options
|
|
432
|
+
def bio(key, bio_format, as_json, refresh, cache_ttl_hours):
|
|
208
433
|
"""Fetch the biography text of KEY (default wiki markup)."""
|
|
209
|
-
|
|
210
|
-
|
|
434
|
+
params = {"action": "getBio", "key": key, "bioFormat": bio_format}
|
|
435
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
436
|
+
data, first, hit = _cached_api(
|
|
437
|
+
"bio",
|
|
438
|
+
params,
|
|
439
|
+
f"getBio {key}",
|
|
440
|
+
refresh=refresh,
|
|
441
|
+
ttl_hours=ttl,
|
|
442
|
+
cacheable=lambda d: bool(d) and isinstance(d[0], dict) and ("bio" in d[0]),
|
|
443
|
+
)
|
|
211
444
|
if as_json:
|
|
212
|
-
click.echo(json.dumps(data, indent=2))
|
|
445
|
+
click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
|
|
213
446
|
return
|
|
214
447
|
text = first.get("bio") or ""
|
|
215
|
-
|
|
448
|
+
if not text:
|
|
449
|
+
click.echo("(no biography text returned)" + (" [cache]" if hit else ""))
|
|
450
|
+
else:
|
|
451
|
+
click.echo(text)
|
|
216
452
|
|
|
217
453
|
|
|
218
454
|
if __name__ == "__main__":
|
package/dist/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAeA,OAAO,EAOL,KAAK,WAAW,EACjB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,KAAK;IACpB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,EAAE,CAAC,EAAE,KAAK,CAAC;IACX,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAWD,eAAO,MAAM,SAAS,QAmC0B,CAAC;AAkSjD,wBAAsB,MAAM,CAC1B,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,WAAW,CAAC,CA4qBtB"}
|
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { realpathSync } from 'node:fs';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
|
-
import { AUDIT_HELP, CONTEXT_HELP, INTEGRATE_HELP, SYNC_HELP, TELEMETRY_HELP, } from './commands/ops/help.js';
|
|
5
|
+
import { AUDIT_HELP, CONTEXT_HELP, DATES_HELP, INTEGRATE_HELP, SYNC_HELP, TELEMETRY_HELP, VERIFY_HELP, } from './commands/ops/help.js';
|
|
6
6
|
import { formatRecordCommandsHelp, renderRecordCommandHelp } from './commands/records/help.js';
|
|
7
7
|
import { resolveRecordCommand } from './commands/records/registry.js';
|
|
8
8
|
import { CliValidationError, EXIT_ERROR, EXIT_OK, EXIT_USAGE, KinloomApiError, formatConflictDetails, } from './errors.js';
|
|
@@ -29,7 +29,9 @@ Research & archive ops:
|
|
|
29
29
|
context Dump privacy-fenced YAML context, relatives, and leads for a person
|
|
30
30
|
integrate Validate and merge a person research package into local YAML
|
|
31
31
|
audit Run 5-check deterministic audit on a person research package
|
|
32
|
+
verify Run full-archive invariant checks over local data/*.yaml files
|
|
32
33
|
sync Diff and sync local YAML + R2 media to a live Cloudflare archive
|
|
34
|
+
dates Compute exact Gregorian weekdays, date diffs, and ages
|
|
33
35
|
telemetry Report local CLI latency, cache hit rate, and failure summary
|
|
34
36
|
|
|
35
37
|
${formatRecordCommandsHelp()}
|
|
@@ -122,7 +124,9 @@ Options:
|
|
|
122
124
|
context: CONTEXT_HELP,
|
|
123
125
|
integrate: INTEGRATE_HELP,
|
|
124
126
|
audit: AUDIT_HELP,
|
|
127
|
+
verify: VERIFY_HELP,
|
|
125
128
|
sync: SYNC_HELP,
|
|
129
|
+
dates: DATES_HELP,
|
|
126
130
|
telemetry: TELEMETRY_HELP,
|
|
127
131
|
};
|
|
128
132
|
function requireStringFlag(value, flagName) {
|
|
@@ -173,6 +177,7 @@ function parseSyncArgs(argv) {
|
|
|
173
177
|
allowDeletes: false,
|
|
174
178
|
deleteTokens: [],
|
|
175
179
|
includeLiving: false,
|
|
180
|
+
verifyLive: false,
|
|
176
181
|
dryRun: false,
|
|
177
182
|
json: false,
|
|
178
183
|
};
|
|
@@ -204,6 +209,10 @@ function parseSyncArgs(argv) {
|
|
|
204
209
|
parsed.includeLiving = true;
|
|
205
210
|
continue;
|
|
206
211
|
}
|
|
212
|
+
if (arg === '--verify-live') {
|
|
213
|
+
parsed.verifyLive = true;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
207
216
|
if (arg === '--dry-run') {
|
|
208
217
|
parsed.dryRun = true;
|
|
209
218
|
continue;
|
|
@@ -685,6 +694,32 @@ export async function runCli(argv, options) {
|
|
|
685
694
|
writeRenderedOutput(io, result.rendered);
|
|
686
695
|
return result.ok ? EXIT_OK : EXIT_ERROR;
|
|
687
696
|
}
|
|
697
|
+
case 'verify': {
|
|
698
|
+
const { values } = safeParseArgs({
|
|
699
|
+
args: rest,
|
|
700
|
+
allowPositionals: false,
|
|
701
|
+
options: {
|
|
702
|
+
repo: { type: 'string' },
|
|
703
|
+
json: { type: 'boolean', default: false },
|
|
704
|
+
},
|
|
705
|
+
});
|
|
706
|
+
const [{ runVerifyCommand }, { measureCommand }] = await Promise.all([
|
|
707
|
+
import('./commands/ops/verify.js'),
|
|
708
|
+
import('./commands/ops/telemetry.js'),
|
|
709
|
+
]);
|
|
710
|
+
const result = await measureCommand({
|
|
711
|
+
subcmd: 'verify',
|
|
712
|
+
extractResultMeta: (res) => ({
|
|
713
|
+
exitCode: res.ok ? EXIT_OK : EXIT_ERROR,
|
|
714
|
+
bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
|
|
715
|
+
}),
|
|
716
|
+
}, () => runVerifyCommand({
|
|
717
|
+
repoDir: values.repo,
|
|
718
|
+
json: values.json,
|
|
719
|
+
}));
|
|
720
|
+
writeRenderedOutput(io, result.rendered);
|
|
721
|
+
return result.ok ? EXIT_OK : EXIT_ERROR;
|
|
722
|
+
}
|
|
688
723
|
case 'sync': {
|
|
689
724
|
const parsed = parseSyncArgs(rest);
|
|
690
725
|
const [{ parseDeleteTargets, parseEntityTypeList, runSyncCommand }, { measureCommand }] = await Promise.all([
|
|
@@ -698,7 +733,7 @@ export async function runCli(argv, options) {
|
|
|
698
733
|
const result = await measureCommand({
|
|
699
734
|
subcmd: parsed.dryRun ? 'sync --dry-run' : 'sync',
|
|
700
735
|
extractResultMeta: (res) => ({
|
|
701
|
-
exitCode: EXIT_OK,
|
|
736
|
+
exitCode: res.liveVerification && !res.liveVerification.ok ? EXIT_ERROR : EXIT_OK,
|
|
702
737
|
bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
|
|
703
738
|
}),
|
|
704
739
|
}, () => runSyncCommand({
|
|
@@ -713,11 +748,81 @@ export async function runCli(argv, options) {
|
|
|
713
748
|
allowDeletes: parsed.allowDeletes,
|
|
714
749
|
explicitDeletes,
|
|
715
750
|
includeLiving: parsed.includeLiving,
|
|
751
|
+
verifyLive: parsed.verifyLive,
|
|
716
752
|
dryRun: parsed.dryRun,
|
|
717
753
|
json: parsed.json,
|
|
718
754
|
fetchImpl,
|
|
719
755
|
}));
|
|
720
756
|
writeRenderedOutput(io, result.rendered);
|
|
757
|
+
return result.liveVerification && !result.liveVerification.ok ? EXIT_ERROR : EXIT_OK;
|
|
758
|
+
}
|
|
759
|
+
case 'dates': {
|
|
760
|
+
const sub = rest[0];
|
|
761
|
+
if (sub !== 'weekday' && sub !== 'diff' && sub !== 'age') {
|
|
762
|
+
throw new CliValidationError(sub
|
|
763
|
+
? `Unknown dates subcommand '${sub}'. Expected \`weekday\`, \`diff\`, or \`age\`.`
|
|
764
|
+
: 'Missing dates subcommand. Expected `weekday`, `diff`, or `age`.');
|
|
765
|
+
}
|
|
766
|
+
const subArgs = rest.slice(1);
|
|
767
|
+
const { values, positionals } = safeParseArgs({
|
|
768
|
+
args: subArgs,
|
|
769
|
+
allowPositionals: true,
|
|
770
|
+
options: {
|
|
771
|
+
at: { type: 'string', multiple: true },
|
|
772
|
+
json: { type: 'boolean', default: false },
|
|
773
|
+
},
|
|
774
|
+
});
|
|
775
|
+
const [{ runDatesCommand }, { measureCommand }] = await Promise.all([
|
|
776
|
+
import('./commands/ops/dates.js'),
|
|
777
|
+
import('./commands/ops/telemetry.js'),
|
|
778
|
+
]);
|
|
779
|
+
const result = await measureCommand({
|
|
780
|
+
subcmd: `dates ${sub}`,
|
|
781
|
+
extractResultMeta: (res) => ({
|
|
782
|
+
exitCode: EXIT_OK,
|
|
783
|
+
bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
|
|
784
|
+
}),
|
|
785
|
+
}, async () => {
|
|
786
|
+
if (sub === 'weekday') {
|
|
787
|
+
if (values.at && values.at.length > 0) {
|
|
788
|
+
throw new CliValidationError('Option `--at` is only valid with `kinloom dates age`.');
|
|
789
|
+
}
|
|
790
|
+
if (positionals.length !== 1) {
|
|
791
|
+
throw new CliValidationError('Usage: kinloom dates weekday <YYYY-MM-DD> [--json]');
|
|
792
|
+
}
|
|
793
|
+
return runDatesCommand({
|
|
794
|
+
subcommand: 'weekday',
|
|
795
|
+
date: positionals[0],
|
|
796
|
+
json: values.json,
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
if (sub === 'diff') {
|
|
800
|
+
if (values.at && values.at.length > 0) {
|
|
801
|
+
throw new CliValidationError('Option `--at` is only valid with `kinloom dates age`.');
|
|
802
|
+
}
|
|
803
|
+
if (positionals.length !== 2) {
|
|
804
|
+
throw new CliValidationError('Usage: kinloom dates diff <start-YYYY-MM-DD> <end-YYYY-MM-DD> [--json]');
|
|
805
|
+
}
|
|
806
|
+
return runDatesCommand({
|
|
807
|
+
subcommand: 'diff',
|
|
808
|
+
startDate: positionals[0],
|
|
809
|
+
endDate: positionals[1],
|
|
810
|
+
json: values.json,
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
if (positionals.length < 1) {
|
|
814
|
+
throw new CliValidationError('Usage: kinloom dates age <birth-YYYY-MM-DD> --at <YYYY-MM-DD> [--at ...] [--json]');
|
|
815
|
+
}
|
|
816
|
+
const [birthDate, ...positionalAts] = positionals;
|
|
817
|
+
const atDates = [...(values.at ?? []), ...positionalAts];
|
|
818
|
+
return runDatesCommand({
|
|
819
|
+
subcommand: 'age',
|
|
820
|
+
birthDate,
|
|
821
|
+
atDates,
|
|
822
|
+
json: values.json,
|
|
823
|
+
});
|
|
824
|
+
});
|
|
825
|
+
writeRenderedOutput(io, result.rendered);
|
|
721
826
|
return EXIT_OK;
|
|
722
827
|
}
|
|
723
828
|
case 'telemetry': {
|