@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,154 @@
1
+ ---
2
+ name: wikitree
3
+ description: Search and read public WikiTree profiles via the bundled uv-based `wikitree` CLI and the public WikiTree API (api.wikitree.com), plus WikiTree One Name Study pages on the website. Covers profile lookup, person search, ancestors, and biographies, plus citation and evidence rules. Use when looking up a WikiTree profile, tracing an ancestral line, checking what WikiTree says about a person, or finding the sources a profile cites. No account or key needed for public profiles.
4
+ ---
5
+
6
+ # WikiTree
7
+
8
+ This skill includes a standalone executable Python CLI at
9
+ `skills/wikitree/scripts/wikitree` using a PEP 723
10
+ `#!/usr/bin/env -S uv run --script` shebang with inline dependencies
11
+ (`click`, `httpx`). No virtualenv setup or API key is required for public
12
+ profiles.
13
+
14
+ - **Public profiles:** no authentication, no key. Only public profiles are
15
+ returned; private profiles come back privacy-limited.
16
+ - **Private profiles:** need a WikiTree member login via the API's
17
+ `clientLogin` flow (multi-step, user goes to WikiTree.com and returns
18
+ with a token). The CLI does not implement login; see "API reference"
19
+ below.
20
+
21
+ ## Bundled CLI (`scripts/wikitree`)
22
+
23
+ Path: `skills/wikitree/scripts/wikitree`
24
+
25
+ ### Search for people
26
+
27
+ ```bash
28
+ # Search public profiles by first and last name
29
+ skills/wikitree/scripts/wikitree search --first Abraham --last Lincoln
30
+
31
+ # Same search, raw JSON
32
+ skills/wikitree/scripts/wikitree search --first Abraham --last Lincoln --limit 5 --json
33
+
34
+ # Narrow by birth location
35
+ skills/wikitree/scripts/wikitree search --last Barton --birth-location "Massachusetts" --limit 10
36
+
37
+ # Require dates on matches (otherwise dateless profiles are also returned)
38
+ skills/wikitree/scripts/wikitree search --first Clara --last Barton --date-include both
39
+ ```
40
+
41
+ ### Look up one profile
42
+
43
+ ```bash
44
+ # By WikiTree ID (<Surname>-<Number> from search output)
45
+ skills/wikitree/scripts/wikitree person <WikiTree-ID>
46
+
47
+ # Raw JSON, all fields
48
+ skills/wikitree/scripts/wikitree person <WikiTree-ID> --fields '*' --json
49
+
50
+ # By numeric user Id
51
+ skills/wikitree/scripts/wikitree person <numeric-id>
52
+ ```
53
+
54
+ ### Ancestors and biography
55
+
56
+ ```bash
57
+ # Two generations of ancestors
58
+ skills/wikitree/scripts/wikitree ancestors <WikiTree-ID> --depth 2
59
+
60
+ # Biography text (wiki markup) for a profile
61
+ skills/wikitree/scripts/wikitree bio <WikiTree-ID>
62
+
63
+ # Biography as HTML instead
64
+ skills/wikitree/scripts/wikitree bio <WikiTree-ID> --format html
65
+ ```
66
+
67
+ ### Disk cache and environment variables
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.
75
+ - `WIKITREE_APP_ID`: application id sent with every API call (default
76
+ `Kinloom`). WikiTree asks every client to send one; calls without an id
77
+ are subject to strict rate limits.
78
+
79
+ ## API reference (verified live 2026-11-24)
80
+
81
+ - Base: `GET https://api.wikitree.com/api.php` (GET or POST, JSON out).
82
+ Docs: `https://github.com/wikitree/wikitree-api` (README plus one
83
+ `.md` file per action).
84
+ - Auth: none for public profiles. Privacy-limited data for private ones.
85
+ - Response shape: a JSON array; each element has `status` (0 or `""` = ok,
86
+ or an error string such as `"Illegal WikiTree ID"`) and the requested
87
+ data.
88
+ - Dates use `YYYY-MM-DD` with `00` for unknown month/day;
89
+ `0000-00-00` means no date at all.
90
+
91
+ | Action | Use | Key params |
92
+ | --- | --- | --- |
93
+ | `getPerson` | One person by WikiTree ID or numeric Id | `key`, `fields`, `bioFormat` (wiki/html/both), `resolveRedirect` (1 = follow redirects) |
94
+ | `getProfile` | Person or Free-Space profile by WikiTree ID or PageId | `key`, `fields` |
95
+ | `searchPerson` | Search like Special:SearchPerson | `FirstName`, `LastName`, `BirthDate`, `DeathDate`, `BirthLocation`, `DeathLocation`, `Gender`, `fatherFirstName`, `fatherLastName`, `motherFirstName`, `motherLastName`, `dateInclude` (both/neither), `dateSpread` (1-20), `lastNameMatch` (all/current/birth/strict), `skipVariants` (1), `sort`, `limit` (1-100, default 10), `start`, `fields` |
96
+ | `getAncestors` | DEPRECATED: the API errors and directs callers to `getPeople` with `ancestors=N` instead. Do not use. | — |
97
+ | `getDescendants` | Descendants following children (still works, verified 2026-11-24) | `key`, `depth`, `fields` |
98
+ | `getRelatives` | Parents, children, siblings, spouses | `keys`, `getParents`, `getChildren`, `getSpouses`, `getSiblings`, `fields` |
99
+ | `getBio` | Biography text for a profile | `key`, `bioFormat` |
100
+ | `getPhotos` | Photos connected to a profile | `key` |
101
+ | `getCategories` | Categories connected to a profile | `key` |
102
+ | `getPeople` | Several profiles by key and/or relationship; also the replacement for `getAncestors` via `ancestors=N` (max 25) and for descendants via `descendants=N` (max 10) | `keys`, `fields`, `ancestors`, `descendants`, `nuclear`, `minGeneration`, `limit`, `start` |
103
+ | `clientLogin` | Authenticate as a member (private profiles) | multi-step token flow, see docs |
104
+
105
+ Default `getPerson` fields are all fields except biography, children and
106
+ spouses; `fields=*` returns everything. The `Mother` and `Father` fields
107
+ hold numeric user Ids; follow them with `getPerson` by Id.
108
+
109
+ ### API behavior notes (verified live 2026-11-24)
110
+
111
+ - Some matches returned by `searchPerson` contain only `Id` and `index`
112
+ (sparse matches); follow up with `person <Id>` for the full profile.
113
+ - `getPeople` returns `status: ""` (empty string) on success rather than
114
+ `0`; the CLI accepts both `0` and `""`.
115
+ - The legacy `getAncestors` action returns a deprecation error directing
116
+ callers to `getPeople` with `ancestors=N`; the CLI's `ancestors` command
117
+ already uses `getPeople`.
118
+
119
+ ## One Name Studies (website)
120
+
121
+ - WikiTree hosts surname-level collaborative projects called One Name
122
+ Studies at `https://www.wikitree.com/wiki/Space:<Surname>_Name_Study`
123
+ and `https://www.wikitree.com/wiki/Project:One_Name_Studies`.
124
+ - Profiles participating in a study carry a `{{One Name Study|name=<Surname>}}`
125
+ sticker and a matching surname study category.
126
+ - Website note: `wikitree.com` profile and space pages can return a WAF
127
+ challenge (HTTP 202, empty body) to plain curl, so read website pages
128
+ through a browser, not curl. The API at `api.wikitree.com` is unaffected
129
+ and answers direct HTTP requests.
130
+
131
+ ## Rules and limits
132
+
133
+ - **WikiTree is a lead, not evidence.** Profiles are collaborative and
134
+ user-contributed; a profile states what other researchers believe, not
135
+ what a record proves. Always follow the profile's cited sources, and
136
+ cross-check against primary records before recording conclusions in
137
+ `data/`. Never copy a WikiTree parentage claim without its citation.
138
+ - **Pre-1700 lines need primary citations.** Pre-1700 profiles in
139
+ particular are expected to cite primary sources. If a profile's only
140
+ sources are compiled genealogies, treat the claim as secondary and look
141
+ for the underlying record.
142
+ - **Document conflicting claims.** WikiTree profiles record disputes in
143
+ Research Notes. When two researchers disagree on parentage or dates,
144
+ keep both claims and their reasoning; do not pick a winner silently.
145
+ - **Living people are excluded** from public search results. Do not try
146
+ to retrieve them through the API.
147
+ - **Rate limits:** WikiTree subjects calls without an `appId` to strict
148
+ rate limits. The CLI always sends one. Keep calls to about one per
149
+ second and do not batch hundreds of lookups in a loop without a pause.
150
+ - **Do not edit through the API.** The API is read-only; edits go
151
+ through the website by a logged-in member. The CLI never writes.
152
+ - **Redirects:** merged profiles redirect to a surviving WikiTree ID.
153
+ Pass `--resolve-redirect` (person) or `resolveRedirect=1` so a lookup
154
+ follows the merge instead of returning the redirect stub.
@@ -0,0 +1,455 @@
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 the public WikiTree API (https://api.wikitree.com/api.php).
10
+
11
+ Read-only. No account or API key is needed for public profiles; every call
12
+ sends an appId (WikiTree rate-limits calls without one). See
13
+ skills/wikitree/SKILL.md for the API reference and rules.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import math
21
+ import os
22
+ import sys
23
+ import time
24
+ from contextlib import contextmanager
25
+ from pathlib import Path
26
+ from typing import Any, Callable, Iterator
27
+
28
+ import click
29
+ import httpx
30
+
31
+ DEFAULT_CACHE_TTL_HOURS = 168.0
32
+ CACHE_SCHEMA = 1
33
+
34
+ API_BASE = "https://api.wikitree.com/api.php"
35
+ DEFAULT_APP_ID = "Kinloom"
36
+ DEFAULT_FIELDS = "Id,Name,FirstName,LastNameAtBirth,BirthDate,DeathDate,BirthLocation"
37
+
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
+
168
+ def _app_id() -> str:
169
+ return os.environ.get("WIKITREE_APP_ID", DEFAULT_APP_ID)
170
+
171
+
172
+ def _client() -> httpx.Client:
173
+ return httpx.Client(timeout=30.0)
174
+
175
+
176
+ def api_call(params: dict) -> list:
177
+ """One GET against the WikiTree API; returns the decoded JSON array."""
178
+ full_params = {"appId": _app_id(), **params}
179
+ try:
180
+ with _client() as client:
181
+ resp = client.get(API_BASE, params=full_params)
182
+ resp.raise_for_status()
183
+ except httpx.HTTPError as exc:
184
+ raise click.ClickException(f"WikiTree API request failed: {exc}") from exc
185
+ try:
186
+ data = resp.json()
187
+ except ValueError as exc:
188
+ raise click.ClickException("WikiTree API returned non-JSON") from exc
189
+ if not isinstance(data, list):
190
+ raise click.ClickException(f"Unexpected API response: {data!r}")
191
+ return data
192
+
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
+
227
+ def check_status(data: list, label: str) -> dict:
228
+ """Raise on a non-zero status element; return the first element."""
229
+ if not data:
230
+ raise click.ClickException(f"{label}: empty response from WikiTree API")
231
+ first = data[0]
232
+ status = first.get("status", 0)
233
+ if status != 0 and status != "":
234
+ raise click.ClickException(f"{label}: {status}")
235
+ return first
236
+
237
+
238
+ def show_person(person: dict) -> None:
239
+ """One compact line per profile, with unknown dates shown as such."""
240
+ name = person.get("Name") or person.get("Id", "?")
241
+ first = person.get("FirstName", "")
242
+ last = person.get("LastNameAtBirth") or person.get("LastNameCurrent", "")
243
+ birth = person.get("BirthDate") or ""
244
+ death = person.get("DeathDate") or ""
245
+ birth = "" if birth in ("", "0000-00-00") else birth
246
+ death = "" if death in ("", "0000-00-00") else death
247
+ place = person.get("BirthLocation", "")
248
+ dates = f"b. {birth}" if birth else "b. ?"
249
+ if death:
250
+ dates += f" d. {death}"
251
+ line = f"{name}: {first} {last} ({dates})"
252
+ if place:
253
+ line += f", born {place}"
254
+ click.echo(line.strip())
255
+
256
+
257
+ @click.group()
258
+ def cli() -> None:
259
+ """Read public WikiTree profiles (search, person, ancestors, bio)."""
260
+
261
+
262
+ @cli.command()
263
+ @click.option("--first", "first_name", default=None, help="First name.")
264
+ @click.option("--last", "last_name", default=None, help="Last name.")
265
+ @click.option("--birth-date", default=None, help="Birth date, YYYY-MM-DD.")
266
+ @click.option("--death-date", default=None, help="Death date, YYYY-MM-DD.")
267
+ @click.option("--birth-location", default=None, help="Birth location.")
268
+ @click.option("--death-location", default=None, help="Death location.")
269
+ @click.option("--date-include", type=click.Choice(["both", "neither"]),
270
+ default=None, help="'both' requires dates on matches.")
271
+ @click.option("--limit", type=click.IntRange(1, 100), default=10,
272
+ show_default=True, help="Results to return (1-100).")
273
+ @click.option("--start", type=int, default=0, show_default=True,
274
+ help="Result offset for paging.")
275
+ @click.option("--fields", default=DEFAULT_FIELDS, show_default=True,
276
+ help="Comma-separated profile fields, or '*'.")
277
+ @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
278
+ @cache_options
279
+ def search(first_name, last_name, birth_date, death_date, birth_location,
280
+ death_location, date_include, limit, start, fields, as_json,
281
+ refresh, cache_ttl_hours):
282
+ """Search person profiles, e.g. search --first Abraham --last Lincoln."""
283
+ if not any([first_name, last_name, birth_date, death_date,
284
+ birth_location, death_location]):
285
+ raise click.BadParameter("give at least one of --first/--last/--birth-date/--death-date/--birth-location/--death-location.")
286
+ params: dict = {"action": "searchPerson", "limit": limit, "start": start,
287
+ "fields": fields}
288
+ if first_name:
289
+ params["FirstName"] = first_name
290
+ if last_name:
291
+ params["LastName"] = last_name
292
+ if birth_date:
293
+ params["BirthDate"] = birth_date
294
+ if death_date:
295
+ params["DeathDate"] = death_date
296
+ if birth_location:
297
+ params["BirthLocation"] = birth_location
298
+ if death_location:
299
+ params["DeathLocation"] = death_location
300
+ if date_include:
301
+ params["dateInclude"] = date_include
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
+ )
313
+ if as_json:
314
+ click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
315
+ return
316
+ matches = first.get("matches", [])
317
+ marker = " [cache]" if hit else ""
318
+ click.echo(f"{first.get('total', len(matches))} match(es), showing {len(matches)}:{marker}")
319
+ for match in matches:
320
+ if "Name" in match or "FirstName" in match:
321
+ show_person(match)
322
+ else:
323
+ # Sparse match (Id only): flag it so the caller follows up.
324
+ click.echo(f"Id {match.get('Id')}: sparse match, run `person {match.get('Id')}` for details")
325
+
326
+
327
+ @cli.command()
328
+ @click.argument("key")
329
+ @click.option("--fields", default=DEFAULT_FIELDS, show_default=True,
330
+ help="Comma-separated profile fields, or '*'.")
331
+ @click.option("--bio-format", type=click.Choice(["wiki", "html", "both"]),
332
+ default=None, help="Include Bio in this format.")
333
+ @click.option("--resolve-redirect", is_flag=True,
334
+ help="Follow merged-profile redirects.")
335
+ @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
336
+ @cache_options
337
+ def person(key, fields, bio_format, resolve_redirect, as_json, refresh, cache_ttl_hours):
338
+ """Fetch one person by WikiTree ID (e.g. <Surname>-<Number>) or numeric Id."""
339
+ params: dict = {"action": "getPerson", "key": key, "fields": fields}
340
+ if bio_format:
341
+ params["bioFormat"] = bio_format
342
+ if "Bio" not in fields.split(",") and fields != "*":
343
+ params["fields"] = fields + ",Bio"
344
+ if resolve_redirect:
345
+ params["resolveRedirect"] = 1
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
+ )
357
+ if as_json:
358
+ click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
359
+ return
360
+ profile = first.get("person") or first.get("profile")
361
+ if not profile:
362
+ raise click.ClickException(f"getPerson {key}: no profile returned")
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)
381
+ if bio_format and profile.get("Bio"):
382
+ click.echo(profile["Bio"])
383
+
384
+
385
+ @cli.command()
386
+ @click.argument("key")
387
+ @click.option("--depth", type=click.IntRange(1, 10), default=4,
388
+ show_default=True, help="Generations to follow (1-10).")
389
+ @click.option("--fields", default=DEFAULT_FIELDS, show_default=True,
390
+ help="Comma-separated profile fields, or '*'.")
391
+ @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
392
+ @cache_options
393
+ def ancestors(key, depth, fields, as_json, refresh, cache_ttl_hours):
394
+ """Fetch ancestors of KEY, following father and mother.
395
+
396
+ Uses getPeople with ancestors=N: the standalone getAncestors action
397
+ is deprecated (the API returns an error telling callers to use
398
+ getPeople instead). The people dict includes the subject profile
399
+ itself, so it is excluded from the listing.
400
+ """
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
+ )
411
+ if as_json:
412
+ click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
413
+ return
414
+ people = first.get("people", {})
415
+ subject = (first.get("resultByKey") or {}).get(key, {})
416
+ subject_id = str(subject.get("Id", ""))
417
+ profiles = [p for pid, p in people.items() if pid != subject_id]
418
+ profiles.sort(key=lambda p: (p.get("BirthDate") or "9999",
419
+ p.get("Name") or ""))
420
+ marker = " [cache]" if hit else ""
421
+ click.echo(f"{len(profiles)} ancestor(s) within {depth} generation(s) of {key}:{marker}")
422
+ for profile in profiles:
423
+ show_person(profile)
424
+
425
+
426
+ @cli.command()
427
+ @click.argument("key")
428
+ @click.option("--format", "bio_format", type=click.Choice(["wiki", "html", "both"]),
429
+ default="wiki", show_default=True, help="Biography format.")
430
+ @click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
431
+ @cache_options
432
+ def bio(key, bio_format, as_json, refresh, cache_ttl_hours):
433
+ """Fetch the biography text of KEY (default wiki markup)."""
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
+ )
444
+ if as_json:
445
+ click.echo(json.dumps(_json_with_cache_hit(data, hit), indent=2))
446
+ return
447
+ text = first.get("bio") or ""
448
+ if not text:
449
+ click.echo("(no biography text returned)" + (" [cache]" if hit else ""))
450
+ else:
451
+ click.echo(text)
452
+
453
+
454
+ if __name__ == "__main__":
455
+ cli()
package/dist/cli.d.ts CHANGED
@@ -8,6 +8,6 @@ export interface RunCliOptions {
8
8
  io?: CliIo;
9
9
  fetchImpl?: typeof fetch;
10
10
  }
11
- export declare const ROOT_HELP = "Usage: kinloom <command> [options]\n\nCommands:\n init Scaffold a thin private family archive repository\n slice-gedcom Slice a combined GEDCOM export into deterministic YAML files\n seed Load local YAML + config and submit an idempotent seed batch\n submit-batch Validate and submit a typed BatchSubmission JSON/YAML file\n export-yaml Export deterministic YAML snapshot with ETag/304 support\n upload-media Validate and upload a media scan or recording via multipart POST\n reconcile Compare cached GET /api/bundle against full compileArchive\n\nGlobal options:\n -h, --help Show help for kinloom or a specific command\n\nEnvironment variables:\n KINLOOM_TOKEN Bearer token used when --token is omitted\n\nExit codes:\n 0 Success\n 1 Runtime, HTTP, or reconciliation drift error\n 2 CLI usage or boundary validation error\n 3 Optimistic concurrency conflict (HTTP 409)";
11
+ export declare const ROOT_HELP: string;
12
12
  export declare function runCli(argv: readonly string[], options?: RunCliOptions): Promise<CliExitCode>;
13
13
  //# sourceMappingURL=cli.d.ts.map
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAYA,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,m6BAqB0B,CAAC;AA8GjD,wBAAsB,MAAM,CAC1B,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,WAAW,CAAC,CAoVtB"}
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"}