@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.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- 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 +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- 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 +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- 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/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { collectLivingNames, compileLivingNamePattern, edtfYear, parseKinloomConfigYaml, parseYaml, resolveEffectiveLiving, } from '@kinloom/core';
|
|
5
|
+
import { CliValidationError } from '../../errors.js';
|
|
6
|
+
export const REDACTED_RELATIVE_LABEL = '[Living relative redacted]';
|
|
7
|
+
const SAFE_PERSON_ID_RE = /^[a-zA-Z0-9_-]+$/;
|
|
8
|
+
export { CONTEXT_HELP } from './help.js';
|
|
9
|
+
function isPlainRecord(value) {
|
|
10
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
async function readOptionalUtf8(filePath) {
|
|
13
|
+
try {
|
|
14
|
+
return await readFile(filePath, 'utf8');
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
if (typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT') {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function splitTopLevelYamlList(text) {
|
|
24
|
+
if (!text) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
const normalized = text.replaceAll('\r\n', '\n');
|
|
28
|
+
const startIdx = normalized.startsWith('- ') ? 0 : normalized.indexOf('\n- ');
|
|
29
|
+
if (startIdx === -1) {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
const body = startIdx === 0 ? normalized : normalized.slice(startIdx + 1);
|
|
33
|
+
return body.split(/\n(?=- )/);
|
|
34
|
+
}
|
|
35
|
+
export function extractYamlBlockId(block) {
|
|
36
|
+
const match = /^- id:\s*["']?([^"'\n\r]+?)["']?\s*(?:\n|$)/.exec(block);
|
|
37
|
+
return match ? match[1].trim() : null;
|
|
38
|
+
}
|
|
39
|
+
export function parseMatchingYamlBlocks(blocks) {
|
|
40
|
+
if (blocks.length === 0) {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
const parsed = parseYaml(blocks.join('\n'));
|
|
44
|
+
if (!Array.isArray(parsed)) {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
return parsed.filter(isPlainRecord);
|
|
48
|
+
}
|
|
49
|
+
function scrubText(value, livingNamePattern) {
|
|
50
|
+
if (!value || !livingNamePattern) {
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
return value.replaceAll(livingNamePattern, REDACTED_RELATIVE_LABEL);
|
|
54
|
+
}
|
|
55
|
+
function scrubDeep(value, livingNamePattern) {
|
|
56
|
+
if (!livingNamePattern) {
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
if (typeof value === 'string') {
|
|
60
|
+
return value.replaceAll(livingNamePattern, REDACTED_RELATIVE_LABEL);
|
|
61
|
+
}
|
|
62
|
+
if (Array.isArray(value)) {
|
|
63
|
+
return value.map((item) => scrubDeep(item, livingNamePattern));
|
|
64
|
+
}
|
|
65
|
+
if (isPlainRecord(value)) {
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [k, v] of Object.entries(value)) {
|
|
68
|
+
out[k] = scrubDeep(v, livingNamePattern);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function extractNumericXref(xref) {
|
|
75
|
+
if (typeof xref !== 'string') {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
const match = /(\d{6,})/.exec(xref);
|
|
79
|
+
return match ? match[1] : null;
|
|
80
|
+
}
|
|
81
|
+
function asNonEmptyString(value) {
|
|
82
|
+
if (value === null || value === undefined) {
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
return String(value).trim();
|
|
86
|
+
}
|
|
87
|
+
function isEffectiveLivingRecord(person, personEvents, privacy) {
|
|
88
|
+
if (person.is_living === true || person.living === true) {
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
const birthEdtf = asNonEmptyString(person.birth_edtf);
|
|
92
|
+
const deathEdtf = asNonEmptyString(person.death_edtf);
|
|
93
|
+
if (resolveEffectiveLiving({
|
|
94
|
+
is_living: Boolean(person.is_living),
|
|
95
|
+
birth_edtf: birthEdtf,
|
|
96
|
+
death_edtf: deathEdtf,
|
|
97
|
+
}, privacy)) {
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
if (deathEdtf.length > 0) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
const years = personEvents
|
|
104
|
+
.map((ev) => edtfYear(typeof ev.edtf_date === 'string' || typeof ev.edtf_date === 'number' ? ev.edtf_date : null))
|
|
105
|
+
.filter((yr) => yr !== null);
|
|
106
|
+
if (years.length > 0) {
|
|
107
|
+
const earliest = Math.min(...years);
|
|
108
|
+
const refYear = privacy.referenceYear ?? 2026;
|
|
109
|
+
const cutoffYears = privacy.livingCutoffYears ?? 101;
|
|
110
|
+
if (earliest > refYear - cutoffYears) {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
function formatLifespan(person) {
|
|
117
|
+
const b = asNonEmptyString(person.birth_edtf) || '?';
|
|
118
|
+
const d = asNonEmptyString(person.death_edtf) || '?';
|
|
119
|
+
return `${b} - ${d}`;
|
|
120
|
+
}
|
|
121
|
+
async function buildAncestryNameIndex(ancestryDir) {
|
|
122
|
+
const index = new Map();
|
|
123
|
+
if (!fs.existsSync(ancestryDir)) {
|
|
124
|
+
return index;
|
|
125
|
+
}
|
|
126
|
+
const entries = await readdir(ancestryDir);
|
|
127
|
+
const jsonFiles = entries.filter((name) => name.endsWith('.json'));
|
|
128
|
+
const namePattern = /"fullName"\s*:\s*"([^"]+)"/;
|
|
129
|
+
const chunkSize = 32;
|
|
130
|
+
for (let i = 0; i < jsonFiles.length; i += chunkSize) {
|
|
131
|
+
const chunk = jsonFiles.slice(i, i + chunkSize);
|
|
132
|
+
await Promise.all(chunk.map(async (fileName) => {
|
|
133
|
+
const fullPath = path.join(ancestryDir, fileName);
|
|
134
|
+
const fh = await fs.promises.open(fullPath, 'r');
|
|
135
|
+
try {
|
|
136
|
+
const buf = Buffer.allocUnsafe(512);
|
|
137
|
+
const { bytesRead } = await fh.read(buf, 0, 512, 0);
|
|
138
|
+
const head = buf.subarray(0, bytesRead).toString('utf8');
|
|
139
|
+
const m = namePattern.exec(head);
|
|
140
|
+
if (m) {
|
|
141
|
+
const key = m[1].trim().toLowerCase();
|
|
142
|
+
if (!index.has(key)) {
|
|
143
|
+
index.set(key, fullPath);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
await fh.close();
|
|
149
|
+
}
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
return index;
|
|
153
|
+
}
|
|
154
|
+
async function findAncestryMatch(ancestryDir, person, nameIndexHolder) {
|
|
155
|
+
if (!ancestryDir || !fs.existsSync(ancestryDir)) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
const numericId = extractNumericXref(person.gedcom_xref);
|
|
159
|
+
if (numericId) {
|
|
160
|
+
const directPath = path.join(ancestryDir, `${numericId}.json`);
|
|
161
|
+
if (fs.existsSync(directPath)) {
|
|
162
|
+
const parsed = JSON.parse(await readFile(directPath, 'utf8'));
|
|
163
|
+
if (isPlainRecord(parsed)) {
|
|
164
|
+
return { matchMode: 'gedcom_xref', jsonPath: directPath, data: parsed };
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const altNames = Array.isArray(person.alt_names) ? person.alt_names : [];
|
|
169
|
+
const targetNames = new Set([person.full_name, ...altNames]
|
|
170
|
+
.filter((n) => typeof n === 'string' && n.trim().length > 0)
|
|
171
|
+
.map((n) => n.trim().toLowerCase()));
|
|
172
|
+
if (targetNames.size === 0) {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
if (!nameIndexHolder.index) {
|
|
176
|
+
nameIndexHolder.index = await buildAncestryNameIndex(ancestryDir);
|
|
177
|
+
}
|
|
178
|
+
for (const name of targetNames) {
|
|
179
|
+
const fullPath = nameIndexHolder.index.get(name);
|
|
180
|
+
if (fullPath) {
|
|
181
|
+
const parsed = JSON.parse(await readFile(fullPath, 'utf8'));
|
|
182
|
+
if (isPlainRecord(parsed)) {
|
|
183
|
+
return { matchMode: 'fullName', jsonPath: fullPath, data: parsed };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
function collectRecordImagesForPerson(raw, personDbId, recordImagesDir, recordImageFiles, sourceTitleByImageId) {
|
|
190
|
+
const imagesByPath = new Map();
|
|
191
|
+
const rawImages = Array.isArray(raw?.recordImages) ? raw.recordImages : [];
|
|
192
|
+
for (const entry of rawImages) {
|
|
193
|
+
if (!isPlainRecord(entry)) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const localPath = typeof entry.local === 'string' ? entry.local : null;
|
|
197
|
+
if (!localPath || !fs.existsSync(localPath)) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const imageId = entry.RecordImageId !== undefined && entry.RecordImageId !== null
|
|
201
|
+
? String(entry.RecordImageId)
|
|
202
|
+
: null;
|
|
203
|
+
const bytes = typeof entry.bytes === 'number' && Number.isFinite(entry.bytes)
|
|
204
|
+
? entry.bytes
|
|
205
|
+
: fs.statSync(localPath).size;
|
|
206
|
+
imagesByPath.set(localPath, {
|
|
207
|
+
path: localPath,
|
|
208
|
+
recordImageId: imageId,
|
|
209
|
+
bytes,
|
|
210
|
+
sourceTitle: imageId ? (sourceTitleByImageId.get(imageId) ?? null) : null,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
if (personDbId && recordImagesDir && recordImageFiles.length > 0) {
|
|
214
|
+
const prefix = `${personDbId}_`;
|
|
215
|
+
for (const file of recordImageFiles) {
|
|
216
|
+
if (!file.startsWith(prefix)) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const fullPath = path.join(recordImagesDir, file);
|
|
220
|
+
if (imagesByPath.has(fullPath)) {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const baseNoExt = file.slice(prefix.length).replace(/\.[^.]+$/, '');
|
|
224
|
+
imagesByPath.set(fullPath, {
|
|
225
|
+
path: fullPath,
|
|
226
|
+
recordImageId: baseNoExt,
|
|
227
|
+
bytes: fs.statSync(fullPath).size,
|
|
228
|
+
sourceTitle: sourceTitleByImageId.get(baseNoExt) ?? null,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return [...imagesByPath.values()].toSorted((a, b) => a.path.localeCompare(b.path));
|
|
233
|
+
}
|
|
234
|
+
function isConfirmedDeceasedRelative(person, livingIds, privacy) {
|
|
235
|
+
if (!person || typeof person.id !== 'string' || livingIds.has(person.id)) {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
if (person.is_living === true || person.living === true) {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
const birthEdtf = asNonEmptyString(person.birth_edtf);
|
|
242
|
+
const deathEdtf = asNonEmptyString(person.death_edtf);
|
|
243
|
+
if (resolveEffectiveLiving({
|
|
244
|
+
is_living: false,
|
|
245
|
+
birth_edtf: birthEdtf,
|
|
246
|
+
death_edtf: deathEdtf,
|
|
247
|
+
}, privacy)) {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
if (deathEdtf.length > 0) {
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
const birthYear = edtfYear(birthEdtf);
|
|
254
|
+
const refYear = privacy.referenceYear ?? 2026;
|
|
255
|
+
const cutoffYears = privacy.livingCutoffYears ?? 101;
|
|
256
|
+
return birthYear !== null && birthYear <= refYear - cutoffYears;
|
|
257
|
+
}
|
|
258
|
+
async function collectDeceasedRelativeRecordImages(params) {
|
|
259
|
+
if (!params.ancestryDir) {
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
const seenPaths = new Set();
|
|
263
|
+
const seenImageIds = new Set();
|
|
264
|
+
for (const img of params.subjectRecordImages) {
|
|
265
|
+
if (img.path) {
|
|
266
|
+
seenPaths.add(img.path);
|
|
267
|
+
}
|
|
268
|
+
if (img.recordImageId) {
|
|
269
|
+
seenImageIds.add(img.recordImageId);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const candidates = [
|
|
273
|
+
...[...params.parentIds].toSorted().map((id) => ({ id, relation: 'parent' })),
|
|
274
|
+
...[...params.spouseIds].toSorted().map((id) => ({ id, relation: 'spouse' })),
|
|
275
|
+
];
|
|
276
|
+
const relativeImages = [];
|
|
277
|
+
for (const { id, relation } of candidates) {
|
|
278
|
+
const rel = params.peopleById.get(id);
|
|
279
|
+
if (!isConfirmedDeceasedRelative(rel, params.livingIds, params.privacy)) {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const match = await findAncestryMatch(params.ancestryDir, rel, params.nameIndexHolder);
|
|
283
|
+
const raw = match?.data ?? null;
|
|
284
|
+
const card = isPlainRecord(raw?.personCard) ? raw.personCard : null;
|
|
285
|
+
if (raw && (raw.isLiving === true || card?.IsLiving === true)) {
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const personDbId = raw && match
|
|
289
|
+
? String(raw.personDbId ?? path.basename(match.jsonPath, '.json'))
|
|
290
|
+
: extractNumericXref(rel.gedcom_xref);
|
|
291
|
+
if (!personDbId) {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
const sourceTitleByImageId = new Map();
|
|
295
|
+
const rawSources = Array.isArray(raw?.sources) ? raw.sources : [];
|
|
296
|
+
for (const src of rawSources) {
|
|
297
|
+
if (!isPlainRecord(src)) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (src.RecordImageId && typeof src.Title === 'string' && !sourceTitleByImageId.has(String(src.RecordImageId))) {
|
|
301
|
+
sourceTitleByImageId.set(String(src.RecordImageId), scrubText(src.Title, params.livingNamePattern));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const relImages = collectRecordImagesForPerson(raw, personDbId, params.recordImagesDir, params.recordImageFiles, sourceTitleByImageId);
|
|
305
|
+
for (const img of relImages) {
|
|
306
|
+
if (seenPaths.has(img.path) || (img.recordImageId && seenImageIds.has(img.recordImageId))) {
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
seenPaths.add(img.path);
|
|
310
|
+
if (img.recordImageId) {
|
|
311
|
+
seenImageIds.add(img.recordImageId);
|
|
312
|
+
}
|
|
313
|
+
relativeImages.push({
|
|
314
|
+
...img,
|
|
315
|
+
relativeId: String(rel.id),
|
|
316
|
+
relativeName: scrubText(asNonEmptyString(rel.full_name), params.livingNamePattern),
|
|
317
|
+
relation,
|
|
318
|
+
personDbId,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return relativeImages;
|
|
323
|
+
}
|
|
324
|
+
function buildAncestrySummary(match, recordImagesDir, recordImageFiles, livingAncestryPids, livingNamePattern) {
|
|
325
|
+
if (!match) {
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
const raw = match.data;
|
|
329
|
+
const card = isPlainRecord(raw.personCard) ? raw.personCard : {};
|
|
330
|
+
if (raw.isLiving === true || card.IsLiving === true) {
|
|
331
|
+
return {
|
|
332
|
+
matchMode: match.matchMode,
|
|
333
|
+
jsonPath: match.jsonPath,
|
|
334
|
+
redacted: true,
|
|
335
|
+
note: REDACTED_RELATIVE_LABEL,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
const personDbId = String(raw.personDbId ?? path.basename(match.jsonPath, '.json'));
|
|
339
|
+
const facts = [];
|
|
340
|
+
let redactedLivingFactsCount = 0;
|
|
341
|
+
for (const factEntry of Array.isArray(raw.facts) ? raw.facts : []) {
|
|
342
|
+
if (!isPlainRecord(factEntry)) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const target = isPlainRecord(factEntry.FactTargetPerson) ? factEntry.FactTargetPerson : null;
|
|
346
|
+
const targetPid = target?.Id !== undefined && target?.Id !== null ? String(target.Id) : null;
|
|
347
|
+
if (target?.IsLiving === true || (targetPid && livingAncestryPids.has(targetPid))) {
|
|
348
|
+
redactedLivingFactsCount += 1;
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const type = (typeof factEntry.TypeString === 'string' && factEntry.TypeString) ||
|
|
352
|
+
(typeof factEntry.Title === 'string' && factEntry.Title) ||
|
|
353
|
+
'Fact';
|
|
354
|
+
const compact = { type };
|
|
355
|
+
if (typeof factEntry.Date === 'string' && factEntry.Date) {
|
|
356
|
+
compact.date = factEntry.Date;
|
|
357
|
+
}
|
|
358
|
+
if (typeof factEntry.Place === 'string' && factEntry.Place) {
|
|
359
|
+
compact.place = scrubText(factEntry.Place, livingNamePattern);
|
|
360
|
+
}
|
|
361
|
+
if (factEntry.Value !== undefined && factEntry.Value !== null && String(factEntry.Value)) {
|
|
362
|
+
compact.value = scrubText(String(factEntry.Value), livingNamePattern);
|
|
363
|
+
}
|
|
364
|
+
if (factEntry.Description !== undefined &&
|
|
365
|
+
factEntry.Description !== null &&
|
|
366
|
+
String(factEntry.Description)) {
|
|
367
|
+
compact.description = scrubText(String(factEntry.Description), livingNamePattern);
|
|
368
|
+
}
|
|
369
|
+
if (typeof target?.FullName === 'string' && target.FullName) {
|
|
370
|
+
compact.targetPerson = {
|
|
371
|
+
name: scrubText(target.FullName, livingNamePattern),
|
|
372
|
+
lifeRange: target.LifeRange
|
|
373
|
+
? String(target.LifeRange).replaceAll('–', '-')
|
|
374
|
+
: null,
|
|
375
|
+
pid: targetPid,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
if (typeof factEntry.SourceCitationCount === 'number' && factEntry.SourceCitationCount > 0) {
|
|
379
|
+
compact.sourceCount = factEntry.SourceCitationCount;
|
|
380
|
+
}
|
|
381
|
+
facts.push(compact);
|
|
382
|
+
}
|
|
383
|
+
const sourceTitleByImageId = new Map();
|
|
384
|
+
const sources = [];
|
|
385
|
+
for (const srcEntry of Array.isArray(raw.sources) ? raw.sources : []) {
|
|
386
|
+
if (!isPlainRecord(srcEntry)) {
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const title = typeof srcEntry.Title === 'string' ? srcEntry.Title : '';
|
|
390
|
+
if (srcEntry.RecordImageId && title && !sourceTitleByImageId.has(String(srcEntry.RecordImageId))) {
|
|
391
|
+
sourceTitleByImageId.set(String(srcEntry.RecordImageId), scrubText(title, livingNamePattern));
|
|
392
|
+
}
|
|
393
|
+
const entry = {
|
|
394
|
+
title: scrubText(title, livingNamePattern),
|
|
395
|
+
};
|
|
396
|
+
if (typeof srcEntry.Detail === 'string' && srcEntry.Detail) {
|
|
397
|
+
entry.detail = scrubText(srcEntry.Detail, livingNamePattern);
|
|
398
|
+
}
|
|
399
|
+
if (srcEntry.CitationId !== undefined && srcEntry.CitationId !== null) {
|
|
400
|
+
entry.citationId = String(srcEntry.CitationId);
|
|
401
|
+
}
|
|
402
|
+
if (srcEntry.DatabaseId !== undefined && srcEntry.DatabaseId !== null) {
|
|
403
|
+
entry.databaseId = String(srcEntry.DatabaseId);
|
|
404
|
+
}
|
|
405
|
+
if (srcEntry.RecordId !== undefined && srcEntry.RecordId !== null) {
|
|
406
|
+
entry.recordId = String(srcEntry.RecordId);
|
|
407
|
+
}
|
|
408
|
+
if (srcEntry.RecordImageId !== undefined && srcEntry.RecordImageId !== null) {
|
|
409
|
+
entry.recordImageId = String(srcEntry.RecordImageId);
|
|
410
|
+
}
|
|
411
|
+
sources.push(entry);
|
|
412
|
+
}
|
|
413
|
+
const recordImages = collectRecordImagesForPerson(raw, personDbId, recordImagesDir, recordImageFiles, sourceTitleByImageId);
|
|
414
|
+
const rawFullName = typeof raw.fullName === 'string'
|
|
415
|
+
? raw.fullName
|
|
416
|
+
: typeof card.FullName === 'string'
|
|
417
|
+
? card.FullName
|
|
418
|
+
: null;
|
|
419
|
+
return {
|
|
420
|
+
matchMode: match.matchMode,
|
|
421
|
+
jsonPath: match.jsonPath,
|
|
422
|
+
personDbId,
|
|
423
|
+
fullName: rawFullName ? scrubText(rawFullName, livingNamePattern) : null,
|
|
424
|
+
lifeRange: card.LifeRange ? String(card.LifeRange).replaceAll('–', '-') : null,
|
|
425
|
+
birthDate: typeof card.BirthDate === 'string' ? card.BirthDate : null,
|
|
426
|
+
birthPlace: typeof card.BirthPlace === 'string'
|
|
427
|
+
? scrubText(card.BirthPlace, livingNamePattern)
|
|
428
|
+
: null,
|
|
429
|
+
deathDate: typeof card.DeathDate === 'string' ? card.DeathDate : null,
|
|
430
|
+
deathPlace: typeof card.DeathPlace === 'string'
|
|
431
|
+
? scrubText(card.DeathPlace, livingNamePattern)
|
|
432
|
+
: null,
|
|
433
|
+
factsUrl: typeof raw.factsUrl === 'string' ? raw.factsUrl : null,
|
|
434
|
+
redactedLivingFactsCount,
|
|
435
|
+
facts,
|
|
436
|
+
sources,
|
|
437
|
+
recordImages,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
export function formatPersonContextMarkdown(ctx) {
|
|
441
|
+
const lines = [];
|
|
442
|
+
const p = ctx.person;
|
|
443
|
+
lines.push(`# Person Context: ${asNonEmptyString(p.full_name)} (\`${asNonEmptyString(p.id)}\`)`);
|
|
444
|
+
lines.push('');
|
|
445
|
+
lines.push(`- Repo: \`${ctx.repoDir}\``);
|
|
446
|
+
lines.push(`- Slug: \`${asNonEmptyString(p.slug)}\` | GEDCOM xref: \`${asNonEmptyString(p.gedcom_xref) || 'none'}\` | Lifespan: \`${formatLifespan(p)}\``);
|
|
447
|
+
lines.push('');
|
|
448
|
+
lines.push('## 1. People Record (`data/people.yaml`)');
|
|
449
|
+
lines.push('```json');
|
|
450
|
+
lines.push(JSON.stringify(p, null, 2));
|
|
451
|
+
lines.push('```');
|
|
452
|
+
lines.push('');
|
|
453
|
+
lines.push('## 2. Immediate Relatives (`data/kinship.yaml`)');
|
|
454
|
+
const groups = [
|
|
455
|
+
['parents', 'Parents'],
|
|
456
|
+
['spouses', 'Spouses'],
|
|
457
|
+
['children', 'Children'],
|
|
458
|
+
];
|
|
459
|
+
for (const [key, label] of groups) {
|
|
460
|
+
const items = ctx.relatives[key];
|
|
461
|
+
lines.push(`### ${label} (${items.length})`);
|
|
462
|
+
if (items.length === 0) {
|
|
463
|
+
lines.push('- None');
|
|
464
|
+
}
|
|
465
|
+
else {
|
|
466
|
+
for (const rel of items) {
|
|
467
|
+
if (rel === REDACTED_RELATIVE_LABEL) {
|
|
468
|
+
lines.push(`- ${REDACTED_RELATIVE_LABEL}`);
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
lines.push(`- \`${rel.id}\` ${rel.full_name} (${rel.lifespan})${rel.gedcom_xref ? ` [xref: \`${rel.gedcom_xref}\`]` : ''}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
lines.push('');
|
|
477
|
+
lines.push(`## 3. Existing Events (${ctx.events.length})`);
|
|
478
|
+
if (ctx.events.length === 0) {
|
|
479
|
+
lines.push('- None');
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
lines.push('```json');
|
|
483
|
+
lines.push(JSON.stringify(ctx.events, null, 2));
|
|
484
|
+
lines.push('```');
|
|
485
|
+
}
|
|
486
|
+
lines.push('');
|
|
487
|
+
lines.push(`## 4. Referenced Places (${ctx.places.length})`);
|
|
488
|
+
if (ctx.places.length === 0) {
|
|
489
|
+
lines.push('- None');
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
lines.push('```json');
|
|
493
|
+
lines.push(JSON.stringify(ctx.places, null, 2));
|
|
494
|
+
lines.push('```');
|
|
495
|
+
}
|
|
496
|
+
lines.push('');
|
|
497
|
+
lines.push(`## 5. Referenced Sources (${ctx.sources.length})`);
|
|
498
|
+
if (ctx.sources.length === 0) {
|
|
499
|
+
lines.push('- None');
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
lines.push('```json');
|
|
503
|
+
lines.push(JSON.stringify(ctx.sources, null, 2));
|
|
504
|
+
lines.push('```');
|
|
505
|
+
}
|
|
506
|
+
lines.push('');
|
|
507
|
+
lines.push(`## 6. Linked Media (${ctx.media.length})`);
|
|
508
|
+
if (ctx.media.length === 0) {
|
|
509
|
+
lines.push('- None');
|
|
510
|
+
}
|
|
511
|
+
else {
|
|
512
|
+
lines.push('```json');
|
|
513
|
+
lines.push(JSON.stringify(ctx.media, null, 2));
|
|
514
|
+
lines.push('```');
|
|
515
|
+
}
|
|
516
|
+
lines.push('');
|
|
517
|
+
lines.push(`## 7. Existing Narratives (${ctx.narratives.length})`);
|
|
518
|
+
if (ctx.narratives.length === 0) {
|
|
519
|
+
lines.push('- None');
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
for (const nar of ctx.narratives) {
|
|
523
|
+
const narId = asNonEmptyString(nar.id);
|
|
524
|
+
const narKind = asNonEmptyString(nar.kind) || 'narrative';
|
|
525
|
+
const narTitle = asNonEmptyString(nar.title);
|
|
526
|
+
const narSources = Array.isArray(nar.source_ids) ? nar.source_ids.length : 0;
|
|
527
|
+
const bodyMd = typeof nar.body_md === 'string' ? nar.body_md : '';
|
|
528
|
+
lines.push(`### \`${narId}\` (${narKind}): ${narTitle}`);
|
|
529
|
+
lines.push(`- slug: \`${asNonEmptyString(nar.slug)}\` | subject_person_id: \`${asNonEmptyString(nar.subject_person_id)}\` | sources: ${narSources} | body_chars: ${bodyMd.length}`);
|
|
530
|
+
if (typeof nar.summary === 'string' && nar.summary) {
|
|
531
|
+
lines.push(`- summary: ${nar.summary}`);
|
|
532
|
+
}
|
|
533
|
+
if (bodyMd) {
|
|
534
|
+
lines.push('');
|
|
535
|
+
lines.push(bodyMd);
|
|
536
|
+
}
|
|
537
|
+
lines.push('');
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
lines.push('## 8. External Facts Export Match');
|
|
541
|
+
if (!ctx.ancestry) {
|
|
542
|
+
lines.push('- No matching external facts JSON found.');
|
|
543
|
+
}
|
|
544
|
+
else if (ctx.ancestry.redacted) {
|
|
545
|
+
lines.push(`- Match: \`${ctx.ancestry.jsonPath}\` (${ctx.ancestry.note})`);
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const a = ctx.ancestry;
|
|
549
|
+
lines.push(`- Matched via \`${a.matchMode}\`: \`${a.jsonPath}\` (personDbId=\`${a.personDbId}\`, lifeRange=\`${a.lifeRange ?? ''}\`)`);
|
|
550
|
+
if (a.redactedLivingFactsCount > 0) {
|
|
551
|
+
lines.push(`- Redacted living-relative facts omitted: ${a.redactedLivingFactsCount}`);
|
|
552
|
+
}
|
|
553
|
+
lines.push(`- Record images on disk (${a.recordImages.length}):`);
|
|
554
|
+
if (a.recordImages.length === 0) {
|
|
555
|
+
lines.push(' - None');
|
|
556
|
+
}
|
|
557
|
+
else {
|
|
558
|
+
for (const img of a.recordImages) {
|
|
559
|
+
lines.push(` - \`${img.path}\` (${img.bytes} bytes)${img.sourceTitle ? ` - ${img.sourceTitle}` : ''}`);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
lines.push(`- Non-living facts (${a.facts.length}):`);
|
|
563
|
+
lines.push('```json');
|
|
564
|
+
lines.push(JSON.stringify(a.facts, null, 2));
|
|
565
|
+
lines.push('```');
|
|
566
|
+
lines.push(`- External sources (${a.sources.length}):`);
|
|
567
|
+
lines.push('```json');
|
|
568
|
+
lines.push(JSON.stringify(a.sources, null, 2));
|
|
569
|
+
lines.push('```');
|
|
570
|
+
}
|
|
571
|
+
const relImgs = ctx.relativeRecordImages;
|
|
572
|
+
lines.push(`- Confirmed-deceased parent/spouse record images on disk, deduplicated (${relImgs.length}):`);
|
|
573
|
+
if (relImgs.length === 0) {
|
|
574
|
+
lines.push(' - None');
|
|
575
|
+
}
|
|
576
|
+
else {
|
|
577
|
+
for (const img of relImgs) {
|
|
578
|
+
lines.push(` - \`${img.path}\` (${img.bytes} bytes) [${img.relation}: \`${img.relativeId}\` ${img.relativeName}]${img.sourceTitle ? ` - ${img.sourceTitle}` : ''}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return `${lines.join('\n')}\n`;
|
|
582
|
+
}
|
|
583
|
+
export async function runContextCommand(options) {
|
|
584
|
+
const repoDir = path.resolve(options.repoDir?.trim() || process.cwd());
|
|
585
|
+
const personId = options.personId.trim();
|
|
586
|
+
if (!personId) {
|
|
587
|
+
throw new CliValidationError('Missing required option `--person <person_id>`.');
|
|
588
|
+
}
|
|
589
|
+
if (!SAFE_PERSON_ID_RE.test(personId)) {
|
|
590
|
+
throw new CliValidationError(`Invalid person_id '${personId}'. Only ASCII letters, digits, _, and - are allowed.`);
|
|
591
|
+
}
|
|
592
|
+
const dataDir = path.join(repoDir, 'data');
|
|
593
|
+
const peopleYamlPath = path.join(dataDir, 'people.yaml');
|
|
594
|
+
if (!fs.existsSync(peopleYamlPath)) {
|
|
595
|
+
throw new CliValidationError(`Archive data/people.yaml not found under ${repoDir}.`);
|
|
596
|
+
}
|
|
597
|
+
const rawAncestryDir = options.ancestryDir?.trim() || process.env.KINLOOM_ANCESTRY_FACTS_DIR?.trim() || '';
|
|
598
|
+
const ancestryDir = rawAncestryDir ? path.resolve(rawAncestryDir) : null;
|
|
599
|
+
const [configText, peopleText, kinshipText, eventsText, placesText, sourcesText, mediaText, narrativesText,] = await Promise.all([
|
|
600
|
+
readOptionalUtf8(path.join(repoDir, 'kinloom.config.yaml')),
|
|
601
|
+
readOptionalUtf8(peopleYamlPath),
|
|
602
|
+
readOptionalUtf8(path.join(dataDir, 'kinship.yaml')),
|
|
603
|
+
readOptionalUtf8(path.join(dataDir, 'events.yaml')),
|
|
604
|
+
readOptionalUtf8(path.join(dataDir, 'places.yaml')),
|
|
605
|
+
readOptionalUtf8(path.join(dataDir, 'sources.yaml')),
|
|
606
|
+
readOptionalUtf8(path.join(dataDir, 'media.yaml')),
|
|
607
|
+
readOptionalUtf8(path.join(dataDir, 'narratives.yaml')),
|
|
608
|
+
]);
|
|
609
|
+
const privacy = configText
|
|
610
|
+
? parseKinloomConfigYaml(configText).privacy
|
|
611
|
+
: {};
|
|
612
|
+
// Pre-filter top-level YAML blocks so large archives stay sub-second.
|
|
613
|
+
const peopleBlocks = splitTopLevelYamlList(peopleText);
|
|
614
|
+
const kinshipBlocks = splitTopLevelYamlList(kinshipText);
|
|
615
|
+
const eventBlocks = splitTopLevelYamlList(eventsText);
|
|
616
|
+
const placeBlocks = splitTopLevelYamlList(placesText);
|
|
617
|
+
const sourceBlocks = splitTopLevelYamlList(sourcesText);
|
|
618
|
+
const mediaBlocks = splitTopLevelYamlList(mediaText);
|
|
619
|
+
const narrativeBlocks = splitTopLevelYamlList(narrativesText);
|
|
620
|
+
const relevantKinship = parseMatchingYamlBlocks(kinshipBlocks.filter((b) => b.includes(personId)));
|
|
621
|
+
const parentIds = new Set();
|
|
622
|
+
const spouseIds = new Set();
|
|
623
|
+
const childIds = new Set();
|
|
624
|
+
for (const edge of relevantKinship) {
|
|
625
|
+
const from = typeof edge.from === 'string' ? edge.from : '';
|
|
626
|
+
const to = typeof edge.to === 'string' ? edge.to : '';
|
|
627
|
+
if (edge.relation === 'parent') {
|
|
628
|
+
if (to === personId && from) {
|
|
629
|
+
parentIds.add(from);
|
|
630
|
+
}
|
|
631
|
+
else if (from === personId && to) {
|
|
632
|
+
childIds.add(to);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
else if (edge.relation === 'child') {
|
|
636
|
+
if (from === personId && to) {
|
|
637
|
+
parentIds.add(to);
|
|
638
|
+
}
|
|
639
|
+
else if (to === personId && from) {
|
|
640
|
+
childIds.add(from);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
else if (edge.relation === 'spouse') {
|
|
644
|
+
if (from === personId && to) {
|
|
645
|
+
spouseIds.add(to);
|
|
646
|
+
}
|
|
647
|
+
else if (to === personId && from) {
|
|
648
|
+
spouseIds.add(from);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
const relativeIdSet = new Set([...parentIds, ...spouseIds, ...childIds]);
|
|
653
|
+
const peopleBlocksToParse = peopleBlocks.filter((block) => {
|
|
654
|
+
const id = extractYamlBlockId(block);
|
|
655
|
+
if (id === personId || (id && relativeIdSet.has(id))) {
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
if (/\b(?:is_living|living):\s*true\b/.test(block)) {
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
const deathMatch = /^\s+death_edtf:\s*(.*)$/m.exec(block);
|
|
662
|
+
const deathVal = deathMatch ? deathMatch[1].trim().replaceAll(/^["']|["']$/g, '') : '';
|
|
663
|
+
return deathVal.length === 0 || deathVal === 'null' || deathVal === '~';
|
|
664
|
+
});
|
|
665
|
+
const parsedPeople = parseMatchingYamlBlocks(peopleBlocksToParse);
|
|
666
|
+
const peopleById = new Map();
|
|
667
|
+
for (const p of parsedPeople) {
|
|
668
|
+
if (typeof p.id === 'string') {
|
|
669
|
+
peopleById.set(p.id, p);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const targetPerson = peopleById.get(personId);
|
|
673
|
+
if (!targetPerson) {
|
|
674
|
+
throw new CliValidationError(`Person '${personId}' not found in ${peopleYamlPath}.`);
|
|
675
|
+
}
|
|
676
|
+
const needEventYearIds = new Set();
|
|
677
|
+
for (const p of parsedPeople) {
|
|
678
|
+
if (typeof p.id !== 'string') {
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const hasDeath = asNonEmptyString(p.death_edtf).length > 0;
|
|
682
|
+
const hasBirth = asNonEmptyString(p.birth_edtf).length > 0;
|
|
683
|
+
if (!p.is_living && !p.living && !hasDeath && !hasBirth) {
|
|
684
|
+
needEventYearIds.add(p.id);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const targetEventBlocks = [];
|
|
688
|
+
const unknownYearEventsByPerson = new Map();
|
|
689
|
+
for (const block of eventBlocks) {
|
|
690
|
+
if (block.includes(personId)) {
|
|
691
|
+
targetEventBlocks.push(block);
|
|
692
|
+
}
|
|
693
|
+
if (needEventYearIds.size > 0) {
|
|
694
|
+
for (const uid of needEventYearIds) {
|
|
695
|
+
if (block.includes(uid)) {
|
|
696
|
+
const dateMatch = /^\s+edtf_date:\s*(.*)$/m.exec(block);
|
|
697
|
+
const dateVal = dateMatch ? dateMatch[1].trim().replaceAll(/^["']|["']$/g, '') : '';
|
|
698
|
+
const list = unknownYearEventsByPerson.get(uid);
|
|
699
|
+
if (list) {
|
|
700
|
+
list.push({ edtf_date: dateVal });
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
unknownYearEventsByPerson.set(uid, [{ edtf_date: dateVal }]);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
const rawPersonEvents = parseMatchingYamlBlocks(targetEventBlocks).filter((ev) => Array.isArray(ev.participants) &&
|
|
710
|
+
ev.participants.some((pt) => isPlainRecord(pt) && pt.person_id === personId));
|
|
711
|
+
const livingIds = new Set();
|
|
712
|
+
const livingAncestryPids = new Set();
|
|
713
|
+
const livingPeopleForNames = [];
|
|
714
|
+
for (const p of parsedPeople) {
|
|
715
|
+
if (typeof p.id !== 'string') {
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
const pEvents = p.id === personId ? rawPersonEvents : (unknownYearEventsByPerson.get(p.id) ?? []);
|
|
719
|
+
if (isEffectiveLivingRecord(p, pEvents, privacy)) {
|
|
720
|
+
livingIds.add(p.id);
|
|
721
|
+
const numId = extractNumericXref(p.gedcom_xref);
|
|
722
|
+
if (numId) {
|
|
723
|
+
livingAncestryPids.add(numId);
|
|
724
|
+
}
|
|
725
|
+
livingPeopleForNames.push({
|
|
726
|
+
is_living: true,
|
|
727
|
+
full_name: asNonEmptyString(p.full_name),
|
|
728
|
+
alt_names: Array.isArray(p.alt_names)
|
|
729
|
+
? p.alt_names.filter((n) => typeof n === 'string')
|
|
730
|
+
: [],
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (livingIds.has(personId)) {
|
|
735
|
+
throw new CliValidationError(`Privacy fence: person '${personId}' is living and excluded from research context dumps.`);
|
|
736
|
+
}
|
|
737
|
+
const livingNamePattern = compileLivingNamePattern(collectLivingNames(livingPeopleForNames));
|
|
738
|
+
const formatRelativeList = (idSet) => [...idSet].toSorted().map((id) => {
|
|
739
|
+
if (livingIds.has(id)) {
|
|
740
|
+
return REDACTED_RELATIVE_LABEL;
|
|
741
|
+
}
|
|
742
|
+
const rel = peopleById.get(id);
|
|
743
|
+
if (!rel) {
|
|
744
|
+
return {
|
|
745
|
+
id,
|
|
746
|
+
full_name: '(missing in people.yaml)',
|
|
747
|
+
lifespan: '? - ?',
|
|
748
|
+
gedcom_xref: null,
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
return {
|
|
752
|
+
id: String(rel.id),
|
|
753
|
+
full_name: scrubText(asNonEmptyString(rel.full_name), livingNamePattern),
|
|
754
|
+
lifespan: formatLifespan(rel),
|
|
755
|
+
gedcom_xref: typeof rel.gedcom_xref === 'string' ? rel.gedcom_xref : null,
|
|
756
|
+
};
|
|
757
|
+
});
|
|
758
|
+
const relatives = {
|
|
759
|
+
parents: formatRelativeList(parentIds),
|
|
760
|
+
spouses: formatRelativeList(spouseIds),
|
|
761
|
+
children: formatRelativeList(childIds),
|
|
762
|
+
};
|
|
763
|
+
const personEventIds = new Set();
|
|
764
|
+
const referencedPlaceIds = new Set();
|
|
765
|
+
const referencedSourceIds = new Set();
|
|
766
|
+
const personEvents = rawPersonEvents.map((ev) => {
|
|
767
|
+
if (typeof ev.id === 'string') {
|
|
768
|
+
personEventIds.add(ev.id);
|
|
769
|
+
}
|
|
770
|
+
const participants = Array.isArray(ev.participants) ? ev.participants : [];
|
|
771
|
+
const hasLivingParticipant = participants.some((pt) => isPlainRecord(pt) && typeof pt.person_id === 'string' && livingIds.has(pt.person_id));
|
|
772
|
+
let clone = structuredClone(ev);
|
|
773
|
+
if (hasLivingParticipant) {
|
|
774
|
+
clone.participants = participants.map((pt) => {
|
|
775
|
+
if (isPlainRecord(pt) && typeof pt.person_id === 'string' && livingIds.has(pt.person_id)) {
|
|
776
|
+
return { person_id: REDACTED_RELATIVE_LABEL, role: pt.role };
|
|
777
|
+
}
|
|
778
|
+
return pt;
|
|
779
|
+
});
|
|
780
|
+
const yr = edtfYear(typeof clone.edtf_date === 'string' || typeof clone.edtf_date === 'number'
|
|
781
|
+
? clone.edtf_date
|
|
782
|
+
: null);
|
|
783
|
+
clone.edtf_date = yr !== null ? String(yr) : '';
|
|
784
|
+
clone.place_id = null;
|
|
785
|
+
clone.summary = 'Event involves a living relative (location and exact date omitted).';
|
|
786
|
+
delete clone.photo_url;
|
|
787
|
+
}
|
|
788
|
+
else if (typeof clone.place_id === 'string' && clone.place_id) {
|
|
789
|
+
referencedPlaceIds.add(clone.place_id);
|
|
790
|
+
}
|
|
791
|
+
clone = scrubDeep(clone, livingNamePattern);
|
|
792
|
+
for (const sRef of Array.isArray(clone.sources) ? clone.sources : []) {
|
|
793
|
+
if (isPlainRecord(sRef) && typeof sRef.source_id === 'string' && sRef.source_id) {
|
|
794
|
+
referencedSourceIds.add(sRef.source_id);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
return clone;
|
|
798
|
+
});
|
|
799
|
+
const targetExtensions = isPlainRecord(targetPerson.extensions) ? targetPerson.extensions : null;
|
|
800
|
+
for (const extSrc of Array.isArray(targetExtensions?.sources) ? targetExtensions.sources : []) {
|
|
801
|
+
if (typeof extSrc === 'string' && extSrc.trim()) {
|
|
802
|
+
referencedSourceIds.add(extSrc.trim());
|
|
803
|
+
}
|
|
804
|
+
else if (isPlainRecord(extSrc) && typeof extSrc.source_id === 'string') {
|
|
805
|
+
referencedSourceIds.add(extSrc.source_id);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const candidateMediaBlocks = mediaBlocks.filter((block) => {
|
|
809
|
+
if (block.includes(personId)) {
|
|
810
|
+
return true;
|
|
811
|
+
}
|
|
812
|
+
for (const eid of personEventIds) {
|
|
813
|
+
if (block.includes(eid)) {
|
|
814
|
+
return true;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return false;
|
|
818
|
+
});
|
|
819
|
+
const personMedia = parseMatchingYamlBlocks(candidateMediaBlocks)
|
|
820
|
+
.filter((item) => {
|
|
821
|
+
const linkedPeople = new Set();
|
|
822
|
+
if (typeof item.person_id === 'string' && item.person_id) {
|
|
823
|
+
linkedPeople.add(item.person_id);
|
|
824
|
+
}
|
|
825
|
+
if (Array.isArray(item.person_ids)) {
|
|
826
|
+
for (const pid of item.person_ids) {
|
|
827
|
+
if (typeof pid === 'string' && pid) {
|
|
828
|
+
linkedPeople.add(pid);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
for (const pid of linkedPeople) {
|
|
833
|
+
if (livingIds.has(pid)) {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return (linkedPeople.has(personId) ||
|
|
838
|
+
(typeof item.event_id === 'string' && personEventIds.has(item.event_id)));
|
|
839
|
+
})
|
|
840
|
+
.map((item) => {
|
|
841
|
+
if (typeof item.source_id === 'string' && item.source_id) {
|
|
842
|
+
referencedSourceIds.add(item.source_id);
|
|
843
|
+
}
|
|
844
|
+
return scrubDeep(structuredClone(item), livingNamePattern);
|
|
845
|
+
});
|
|
846
|
+
const personNarratives = parseMatchingYamlBlocks(narrativeBlocks.filter((b) => b.includes(personId)))
|
|
847
|
+
.filter((nar) => nar.subject_person_id === personId ||
|
|
848
|
+
(Array.isArray(nar.person_ids) && nar.person_ids.includes(personId)))
|
|
849
|
+
.map((nar) => {
|
|
850
|
+
for (const sid of Array.isArray(nar.source_ids) ? nar.source_ids : []) {
|
|
851
|
+
if (typeof sid === 'string' && sid) {
|
|
852
|
+
referencedSourceIds.add(sid);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
for (const plid of Array.isArray(nar.place_ids) ? nar.place_ids : []) {
|
|
856
|
+
if (typeof plid === 'string' && plid) {
|
|
857
|
+
referencedPlaceIds.add(plid);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
const clone = structuredClone(nar);
|
|
861
|
+
if (Array.isArray(clone.person_ids)) {
|
|
862
|
+
clone.person_ids = clone.person_ids.map((pid) => typeof pid === 'string' && livingIds.has(pid) ? REDACTED_RELATIVE_LABEL : pid);
|
|
863
|
+
}
|
|
864
|
+
return scrubDeep(clone, livingNamePattern);
|
|
865
|
+
});
|
|
866
|
+
const referencedPlaces = parseMatchingYamlBlocks(placeBlocks.filter((b) => {
|
|
867
|
+
const id = extractYamlBlockId(b);
|
|
868
|
+
return Boolean(id && referencedPlaceIds.has(id));
|
|
869
|
+
})).toSorted((a, b) => String(a.id ?? '').localeCompare(String(b.id ?? '')));
|
|
870
|
+
const referencedSources = parseMatchingYamlBlocks(sourceBlocks.filter((b) => {
|
|
871
|
+
const id = extractYamlBlockId(b);
|
|
872
|
+
return Boolean(id && referencedSourceIds.has(id));
|
|
873
|
+
}))
|
|
874
|
+
.map((s) => scrubDeep(structuredClone(s), livingNamePattern))
|
|
875
|
+
.toSorted((a, b) => String(a.id ?? '').localeCompare(String(b.id ?? '')));
|
|
876
|
+
const sanitizedTargetPerson = scrubDeep(structuredClone(targetPerson), livingNamePattern);
|
|
877
|
+
const nameIndexHolder = { index: null };
|
|
878
|
+
const recordImagesDir = ancestryDir ? path.join(ancestryDir, 'record_images') : null;
|
|
879
|
+
const recordImageFiles = recordImagesDir && fs.existsSync(recordImagesDir) ? await readdir(recordImagesDir) : [];
|
|
880
|
+
const ancestryMatch = await findAncestryMatch(ancestryDir, targetPerson, nameIndexHolder);
|
|
881
|
+
const ancestrySummary = buildAncestrySummary(ancestryMatch, recordImagesDir, recordImageFiles, livingAncestryPids, livingNamePattern);
|
|
882
|
+
const subjectRecordImages = ancestrySummary && !ancestrySummary.redacted ? ancestrySummary.recordImages : [];
|
|
883
|
+
const relativeRecordImages = await collectDeceasedRelativeRecordImages({
|
|
884
|
+
parentIds,
|
|
885
|
+
spouseIds,
|
|
886
|
+
peopleById,
|
|
887
|
+
livingIds,
|
|
888
|
+
privacy,
|
|
889
|
+
ancestryDir,
|
|
890
|
+
recordImagesDir,
|
|
891
|
+
recordImageFiles,
|
|
892
|
+
subjectRecordImages,
|
|
893
|
+
livingNamePattern,
|
|
894
|
+
nameIndexHolder,
|
|
895
|
+
});
|
|
896
|
+
const context = {
|
|
897
|
+
repoDir,
|
|
898
|
+
person: sanitizedTargetPerson,
|
|
899
|
+
relatives,
|
|
900
|
+
events: personEvents,
|
|
901
|
+
places: referencedPlaces,
|
|
902
|
+
sources: referencedSources,
|
|
903
|
+
media: personMedia,
|
|
904
|
+
narratives: personNarratives,
|
|
905
|
+
ancestry: ancestrySummary,
|
|
906
|
+
relativeRecordImages,
|
|
907
|
+
};
|
|
908
|
+
const rendered = options.json
|
|
909
|
+
? `${JSON.stringify(context, null, 2)}\n`
|
|
910
|
+
: formatPersonContextMarkdown(context);
|
|
911
|
+
return {
|
|
912
|
+
context,
|
|
913
|
+
rendered,
|
|
914
|
+
bytesOut: Buffer.byteLength(rendered, 'utf8'),
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
//# sourceMappingURL=context.js.map
|