@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,1063 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { ArchiveBundleSchema, KinshipEdgeSchema, MediaItemSchema, NarrativeSchema, PlaceSchema, RawEventSchema, RawPersonSchema, SourceRecordSchema, compileArchive, extractNarrativeCitations, getMediaPersonIds, mergeEventSources, parseEventsYaml, parseKinloomConfigYaml, parseKinshipYaml, parseMediaYaml, parseNarrativeEnrichmentsYaml, parseNarrativesYaml, parsePeopleYaml, parsePlacesYaml, parseSourcesYaml, resolveEffectiveLiving, serializeEventsYaml, serializeKinshipYaml, serializeMediaYaml, serializeNarrativesYaml, serializePeopleYaml, serializePlacesYaml, serializeSourcesYaml, validateMediaForPrivacy, validateNarrativeCitations, } from '@kinloom/core';
5
+ import { CliValidationError } from '../../errors.js';
6
+ const YEAR_ONLY_RE = /^\d{4}$/;
7
+ const SAFE_PERSON_ID_RE = /^[a-zA-Z0-9_-]+$/;
8
+ const ALLOWED_PATCH_KEYS = new Set([
9
+ 'person_id',
10
+ 'person_updates',
11
+ 'events',
12
+ 'remove_event_ids',
13
+ 'places',
14
+ 'sources',
15
+ 'remove_source_ids',
16
+ 'media',
17
+ 'remove_media_ids',
18
+ 'kinship',
19
+ 'narratives',
20
+ ]);
21
+ const ALLOWED_PERSON_UPDATE_KEYS = new Set([
22
+ 'id',
23
+ 'slug',
24
+ 'gedcom_xref',
25
+ 'full_name',
26
+ 'given_name',
27
+ 'surname',
28
+ 'alt_names',
29
+ 'sex',
30
+ 'is_living',
31
+ 'living',
32
+ 'lineage_group',
33
+ 'branch',
34
+ 'birth_edtf',
35
+ 'death_edtf',
36
+ 'birth_date',
37
+ 'death_date',
38
+ 'portrait_url',
39
+ 'thumb_url',
40
+ 'has_primary_source',
41
+ 'extensions',
42
+ 'bio',
43
+ 'biography',
44
+ 'summary',
45
+ 'research_notes',
46
+ 'sources',
47
+ ]);
48
+ export { INTEGRATE_HELP } from './help.js';
49
+ function parseOptionalStringList(raw, label) {
50
+ if (raw === undefined) {
51
+ return [];
52
+ }
53
+ if (!Array.isArray(raw)) {
54
+ throw new Error(`${label} must be an array of non-empty strings.`);
55
+ }
56
+ const out = [];
57
+ const seen = new Set();
58
+ for (let i = 0; i < raw.length; i += 1) {
59
+ const item = raw[i];
60
+ if (typeof item !== 'string' || item.trim().length === 0) {
61
+ throw new Error(`${label}[${i}] must be a non-empty string.`);
62
+ }
63
+ const trimmed = item.trim();
64
+ if (!seen.has(trimmed)) {
65
+ seen.add(trimmed);
66
+ out.push(trimmed);
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+ function isPlainObject(value) {
72
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
73
+ }
74
+ function readOptionalUtf8(filePath) {
75
+ if (!fs.existsSync(filePath)) {
76
+ return '';
77
+ }
78
+ return fs.readFileSync(filePath, 'utf8');
79
+ }
80
+ function sha256File(filePath) {
81
+ const buf = fs.readFileSync(filePath);
82
+ return {
83
+ sizeBytes: buf.byteLength,
84
+ sha256: createHash('sha256').update(buf).digest('hex'),
85
+ };
86
+ }
87
+ function dedupeStrings(existing, additions) {
88
+ const out = [];
89
+ const seen = new Set();
90
+ for (const raw of [...(existing ?? []), ...(additions ?? [])]) {
91
+ if (typeof raw !== 'string') {
92
+ continue;
93
+ }
94
+ const trimmed = raw.trim();
95
+ if (!trimmed || seen.has(trimmed)) {
96
+ continue;
97
+ }
98
+ seen.add(trimmed);
99
+ out.push(trimmed);
100
+ }
101
+ return out;
102
+ }
103
+ function dedupeExtensionSources(existing, additions) {
104
+ const out = [];
105
+ const seen = new Set();
106
+ const keyFor = (entry) => {
107
+ if (typeof entry === 'string') {
108
+ return `str:${entry.trim()}`;
109
+ }
110
+ if (isPlainObject(entry) && typeof entry.source_id === 'string') {
111
+ return `sid:${entry.source_id}`;
112
+ }
113
+ return `json:${JSON.stringify(entry)}`;
114
+ };
115
+ for (const entry of [...(existing ?? []), ...(additions ?? [])]) {
116
+ if (entry === null || entry === undefined) {
117
+ continue;
118
+ }
119
+ const key = keyFor(entry);
120
+ if (seen.has(key)) {
121
+ continue;
122
+ }
123
+ seen.add(key);
124
+ out.push(structuredClone(entry));
125
+ }
126
+ return out;
127
+ }
128
+ // Incoming roles replace a person's existing roles on the event. A person keeps
129
+ // several roles only when the incoming patch lists each one explicitly.
130
+ function dedupeParticipants(existing, additions) {
131
+ const incomingIds = new Set((additions ?? []).map((pt) => pt.person_id));
132
+ const retained = (existing ?? []).filter((pt) => !incomingIds.has(pt.person_id));
133
+ const out = [];
134
+ const seen = new Set();
135
+ for (const pt of [...retained, ...(additions ?? [])]) {
136
+ const key = `${pt.person_id}|${pt.role}`;
137
+ if (seen.has(key)) {
138
+ continue;
139
+ }
140
+ seen.add(key);
141
+ out.push({ person_id: pt.person_id, role: pt.role });
142
+ }
143
+ return out;
144
+ }
145
+ function normalizeAndValidatePatch(rawPatch, expectedPersonId) {
146
+ if (!isPlainObject(rawPatch)) {
147
+ throw new Error('patch.json root must be a JSON object.');
148
+ }
149
+ for (const key of Object.keys(rawPatch)) {
150
+ if (!ALLOWED_PATCH_KEYS.has(key)) {
151
+ throw new Error(`Unknown top-level key '${key}' in patch.json.`);
152
+ }
153
+ }
154
+ if (typeof rawPatch.person_id !== 'string' || rawPatch.person_id !== expectedPersonId) {
155
+ throw new Error(`patch.json person_id '${String(rawPatch.person_id)}' does not match --person '${expectedPersonId}'.`);
156
+ }
157
+ const rawUpdates = rawPatch.person_updates ?? null;
158
+ if (rawUpdates !== null && !isPlainObject(rawUpdates)) {
159
+ throw new Error('patch.json person_updates must be an object when provided.');
160
+ }
161
+ if (rawUpdates) {
162
+ for (const key of Object.keys(rawUpdates)) {
163
+ if (!ALLOWED_PERSON_UPDATE_KEYS.has(key)) {
164
+ throw new Error(`Unknown key '${key}' in patch.json person_updates.`);
165
+ }
166
+ }
167
+ }
168
+ const readArrayField = (field) => {
169
+ const val = rawPatch[field];
170
+ if (val === undefined) {
171
+ return [];
172
+ }
173
+ if (!Array.isArray(val)) {
174
+ throw new Error(`patch.json '${field}' must be an array.`);
175
+ }
176
+ return val;
177
+ };
178
+ return {
179
+ person_id: rawPatch.person_id,
180
+ person_updates: rawUpdates,
181
+ events: readArrayField('events'),
182
+ remove_event_ids: parseOptionalStringList(rawPatch.remove_event_ids, 'patch.json remove_event_ids'),
183
+ places: readArrayField('places'),
184
+ sources: readArrayField('sources'),
185
+ remove_source_ids: parseOptionalStringList(rawPatch.remove_source_ids, 'patch.json remove_source_ids'),
186
+ media: readArrayField('media'),
187
+ remove_media_ids: parseOptionalStringList(rawPatch.remove_media_ids, 'patch.json remove_media_ids'),
188
+ kinship: readArrayField('kinship'),
189
+ narratives: readArrayField('narratives'),
190
+ };
191
+ }
192
+ function assertValidPlaceCoordinates(place, label) {
193
+ if (!isPlainObject(place)) {
194
+ throw new Error(`${label} must be an object.`);
195
+ }
196
+ const placeIdLabel = typeof place.id === 'string' ? place.id : 'unknown';
197
+ const hasLng = place.lng !== undefined && place.lng !== null;
198
+ const hasLon = place.lon !== undefined && place.lon !== null;
199
+ if (!hasLng && !hasLon) {
200
+ throw new Error(`${label} (${placeIdLabel}) is missing coordinates (lat/lng).`);
201
+ }
202
+ if (hasLng && hasLon && Number(place.lng) !== Number(place.lon)) {
203
+ throw new Error(`${label} (${placeIdLabel}) specifies conflicting lng (${String(place.lng)}) and lon (${String(place.lon)}).`);
204
+ }
205
+ const lat = Number(place.lat);
206
+ const lng = Number(hasLng ? place.lng : place.lon);
207
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
208
+ throw new Error(`${label} (${placeIdLabel}) has non-finite coordinates.`);
209
+ }
210
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
211
+ throw new Error(`${label} (${placeIdLabel}) coordinates out of range: (${lat}, ${lng}).`);
212
+ }
213
+ if (Math.abs(lat) < 1e-9 && Math.abs(lng) < 1e-9) {
214
+ throw new Error(`${label} (${placeIdLabel}) has forbidden (0, 0) coordinates.`);
215
+ }
216
+ const copy = { ...place, lat, lng };
217
+ delete copy.lon;
218
+ return copy;
219
+ }
220
+ function mergePersonUpdates(existingPerson, updates, privacyConfig) {
221
+ if (!updates || Object.keys(updates).length === 0) {
222
+ return { updated: structuredClone(existingPerson), changed: false };
223
+ }
224
+ if (updates.id !== undefined && updates.id !== existingPerson.id) {
225
+ throw new Error(`person_updates cannot change person id from '${existingPerson.id}' to '${String(updates.id)}'.`);
226
+ }
227
+ if (updates.is_living === true || updates.living === true) {
228
+ throw new Error(`person_updates cannot mark target '${existingPerson.id}' as living.`);
229
+ }
230
+ if (updates.birth_edtf !== undefined &&
231
+ updates.birth_date !== undefined &&
232
+ String(updates.birth_edtf) !== String(updates.birth_date)) {
233
+ throw new Error('person_updates has conflicting birth_edtf and birth_date.');
234
+ }
235
+ if (updates.death_edtf !== undefined &&
236
+ updates.death_date !== undefined &&
237
+ String(updates.death_edtf) !== String(updates.death_date)) {
238
+ throw new Error('person_updates has conflicting death_edtf and death_date.');
239
+ }
240
+ if (updates.bio !== undefined &&
241
+ updates.biography !== undefined &&
242
+ String(updates.bio) !== String(updates.biography)) {
243
+ throw new Error('person_updates has conflicting bio and biography.');
244
+ }
245
+ const next = structuredClone(existingPerson);
246
+ const directFields = [
247
+ 'slug',
248
+ 'gedcom_xref',
249
+ 'full_name',
250
+ 'given_name',
251
+ 'surname',
252
+ 'sex',
253
+ 'lineage_group',
254
+ 'branch',
255
+ 'portrait_url',
256
+ 'thumb_url',
257
+ 'has_primary_source',
258
+ ];
259
+ for (const field of directFields) {
260
+ if (updates[field] !== undefined) {
261
+ next[field] = updates[field];
262
+ }
263
+ }
264
+ const birthVal = updates.birth_edtf !== undefined ? updates.birth_edtf : updates.birth_date;
265
+ if (birthVal !== undefined) {
266
+ next.birth_edtf = birthVal === null ? '' : String(birthVal);
267
+ }
268
+ const deathVal = updates.death_edtf !== undefined ? updates.death_edtf : updates.death_date;
269
+ if (deathVal !== undefined) {
270
+ next.death_edtf = deathVal === null ? '' : String(deathVal);
271
+ }
272
+ if (updates.alt_names !== undefined) {
273
+ if (!Array.isArray(updates.alt_names)) {
274
+ throw new Error('person_updates.alt_names must be an array of strings.');
275
+ }
276
+ next.alt_names = dedupeStrings(existingPerson.alt_names, updates.alt_names);
277
+ }
278
+ const existingExt = isPlainObject(existingPerson.extensions)
279
+ ? structuredClone(existingPerson.extensions)
280
+ : {};
281
+ let extTouched = false;
282
+ if (updates.extensions !== undefined) {
283
+ if (!isPlainObject(updates.extensions)) {
284
+ throw new Error('person_updates.extensions must be an object.');
285
+ }
286
+ for (const [k, v] of Object.entries(updates.extensions)) {
287
+ if (k === 'sources' && Array.isArray(v)) {
288
+ existingExt.sources = dedupeExtensionSources(Array.isArray(existingExt.sources) ? existingExt.sources : [], v);
289
+ }
290
+ else {
291
+ existingExt[k] = structuredClone(v);
292
+ }
293
+ }
294
+ extTouched = true;
295
+ }
296
+ const bioVal = updates.biography !== undefined ? updates.biography : updates.bio;
297
+ if (bioVal !== undefined) {
298
+ existingExt.biography = String(bioVal);
299
+ extTouched = true;
300
+ }
301
+ if (updates.summary !== undefined) {
302
+ existingExt.summary = String(updates.summary);
303
+ extTouched = true;
304
+ }
305
+ if (updates.research_notes !== undefined) {
306
+ existingExt.research_notes = String(updates.research_notes);
307
+ extTouched = true;
308
+ }
309
+ if (updates.sources !== undefined) {
310
+ if (!Array.isArray(updates.sources)) {
311
+ throw new Error('person_updates.sources must be an array.');
312
+ }
313
+ existingExt.sources = dedupeExtensionSources(Array.isArray(existingExt.sources) ? existingExt.sources : [], updates.sources);
314
+ extTouched = true;
315
+ }
316
+ if (extTouched) {
317
+ next.extensions = existingExt;
318
+ }
319
+ const parsed = RawPersonSchema.parse(next);
320
+ if (resolveEffectiveLiving(parsed, privacyConfig)) {
321
+ throw new Error(`Refusing update: merged person '${parsed.id}' resolves as living under privacy rules.`);
322
+ }
323
+ const changed = JSON.stringify(existingPerson) !== JSON.stringify(parsed);
324
+ return { updated: parsed, changed };
325
+ }
326
+ function upsertById(existingList, incomingList, parseItem, mergeExisting) {
327
+ const result = existingList.map((item) => structuredClone(item));
328
+ const idxById = new Map(result.map((item, idx) => [item.id, idx]));
329
+ let added = 0;
330
+ let updated = 0;
331
+ let unchanged = 0;
332
+ for (const raw of incomingList) {
333
+ const incoming = parseItem(raw);
334
+ const existingIdx = idxById.get(incoming.id);
335
+ if (existingIdx === undefined) {
336
+ idxById.set(incoming.id, result.length);
337
+ result.push(incoming);
338
+ added += 1;
339
+ continue;
340
+ }
341
+ const prev = result[existingIdx];
342
+ const merged = mergeExisting ? parseItem(mergeExisting(prev, incoming)) : incoming;
343
+ if (JSON.stringify(prev) === JSON.stringify(merged)) {
344
+ unchanged += 1;
345
+ }
346
+ else {
347
+ result[existingIdx] = merged;
348
+ updated += 1;
349
+ }
350
+ }
351
+ return { items: result, counts: { added, updated, unchanged } };
352
+ }
353
+ function upsertKinship(existingList, incomingList) {
354
+ const result = existingList.map((item) => structuredClone(item));
355
+ const keyOf = (edge) => `${edge.from}|${edge.to}|${edge.relation}`;
356
+ const idxByKey = new Map(result.map((edge, idx) => [keyOf(edge), idx]));
357
+ let added = 0;
358
+ let updated = 0;
359
+ let unchanged = 0;
360
+ for (const raw of incomingList) {
361
+ const incoming = KinshipEdgeSchema.parse(raw);
362
+ const key = keyOf(incoming);
363
+ const existingIdx = idxByKey.get(key);
364
+ if (existingIdx === undefined) {
365
+ idxByKey.set(key, result.length);
366
+ result.push(incoming);
367
+ added += 1;
368
+ continue;
369
+ }
370
+ const prev = result[existingIdx];
371
+ const merged = KinshipEdgeSchema.parse({
372
+ ...prev,
373
+ ...incoming,
374
+ family_xref: incoming.family_xref !== undefined ? incoming.family_xref : prev.family_xref,
375
+ });
376
+ if (JSON.stringify(prev) === JSON.stringify(merged)) {
377
+ unchanged += 1;
378
+ }
379
+ else {
380
+ result[existingIdx] = merged;
381
+ updated += 1;
382
+ }
383
+ }
384
+ return { items: result, counts: { added, updated, unchanged } };
385
+ }
386
+ function detectMediaLayout(repoDir) {
387
+ const archiveMediaRoot = path.join(repoDir, 'archive-media');
388
+ if (fs.existsSync(archiveMediaRoot) && fs.statSync(archiveMediaRoot).isDirectory()) {
389
+ // Archives with an `archive-media/` directory store `/media/scans/<file>` at
390
+ // `archive-media/media/scans/<file>` so R2 uploads map directly to `media/scans/<file>`.
391
+ return {
392
+ layout: 'archive-media',
393
+ mediaUrlRoot: archiveMediaRoot,
394
+ scanDestDir: path.join(archiveMediaRoot, 'media', 'scans'),
395
+ scanUrlPrefix: '/media/scans/',
396
+ r2KeyPrefix: 'media/scans/',
397
+ };
398
+ }
399
+ return {
400
+ layout: 'media',
401
+ mediaUrlRoot: repoDir,
402
+ scanDestDir: path.join(repoDir, 'media'),
403
+ scanUrlPrefix: '/media/',
404
+ r2KeyPrefix: 'media/',
405
+ };
406
+ }
407
+ function resolveMediaDiskPath(fileUrl, repoDir, mediaLayout) {
408
+ if (!fileUrl.startsWith('/media/')) {
409
+ throw new Error(`Media file URL must start with '/media/', got '${fileUrl}'.`);
410
+ }
411
+ const relPosix = fileUrl.slice(1);
412
+ const parts = relPosix.split('/');
413
+ if (parts.some((seg) => !seg || seg === '.' || seg === '..')) {
414
+ throw new Error(`Unsafe media file URL '${fileUrl}'.`);
415
+ }
416
+ const diskPath = path.resolve(mediaLayout.mediaUrlRoot, ...parts);
417
+ const publicMediaDir = path.resolve(repoDir, 'public', 'media');
418
+ if (diskPath === publicMediaDir || diskPath.startsWith(`${publicMediaDir}${path.sep}`)) {
419
+ throw new Error(`Media file URL '${fileUrl}' resolves inside forbidden public/media/.`);
420
+ }
421
+ const rootPrefix = `${path.resolve(mediaLayout.mediaUrlRoot)}${path.sep}`;
422
+ if (!diskPath.startsWith(rootPrefix)) {
423
+ throw new Error(`Media file URL '${fileUrl}' escapes media root.`);
424
+ }
425
+ return diskPath;
426
+ }
427
+ function planScanStaging(repoDir, packageDir, mediaLayout) {
428
+ const scansSourceDir = path.join(packageDir, 'scans');
429
+ if (!fs.existsSync(scansSourceDir)) {
430
+ return [];
431
+ }
432
+ const entries = fs
433
+ .readdirSync(scansSourceDir, { withFileTypes: true })
434
+ .toSorted((a, b) => a.name.localeCompare(b.name));
435
+ const planned = [];
436
+ const publicDir = path.resolve(repoDir, 'public');
437
+ for (const entry of entries) {
438
+ if (entry.isDirectory()) {
439
+ throw new Error(`Unexpected subdirectory '${entry.name}' inside ${scansSourceDir}. Place scan files directly in scans/.`);
440
+ }
441
+ if (!entry.isFile()) {
442
+ continue;
443
+ }
444
+ if (entry.name.includes('/') ||
445
+ entry.name.includes('\\') ||
446
+ entry.name === '..' ||
447
+ entry.name === '.') {
448
+ throw new Error(`Unsafe scan filename '${entry.name}'.`);
449
+ }
450
+ const sourcePath = path.join(scansSourceDir, entry.name);
451
+ const destPath = path.resolve(mediaLayout.scanDestDir, entry.name);
452
+ if (destPath === publicDir || destPath.startsWith(`${publicDir}${path.sep}`)) {
453
+ throw new Error(`Scan destination '${destPath}' must never target public/.`);
454
+ }
455
+ const { sizeBytes, sha256 } = sha256File(sourcePath);
456
+ if (sizeBytes === 0) {
457
+ throw new Error(`Scan file '${sourcePath}' is empty (0 bytes).`);
458
+ }
459
+ let alreadyIdentical = false;
460
+ if (fs.existsSync(destPath)) {
461
+ const existing = sha256File(destPath);
462
+ alreadyIdentical = existing.sha256 === sha256;
463
+ }
464
+ planned.push({
465
+ filename: entry.name,
466
+ sourcePath,
467
+ destPath,
468
+ url: `${mediaLayout.scanUrlPrefix}${entry.name}`,
469
+ r2Key: `${mediaLayout.r2KeyPrefix}${entry.name}`,
470
+ sizeBytes,
471
+ sha256,
472
+ alreadyIdentical,
473
+ });
474
+ }
475
+ return planned;
476
+ }
477
+ export function auditBundlePrivacy(bundle, mode) {
478
+ const livingPeople = bundle.people.filter((p) => Boolean(p.is_living));
479
+ const livingIds = new Set(livingPeople.map((p) => p.id));
480
+ const leaks = [];
481
+ for (const person of livingPeople) {
482
+ const birthEdtf = person.birth_edtf.trim();
483
+ if (mode === 'public') {
484
+ if (person.full_name !== 'Living') {
485
+ leaks.push(`public:person:${person.id}:full_name`);
486
+ }
487
+ if (birthEdtf.length > 0) {
488
+ leaks.push(`public:person:${person.id}:birth_edtf`);
489
+ }
490
+ if (person.alt_names.length > 0) {
491
+ leaks.push(`public:person:${person.id}:alt_names`);
492
+ }
493
+ }
494
+ else if (birthEdtf.length > 0 && !YEAR_ONLY_RE.test(birthEdtf)) {
495
+ leaks.push(`private:person:${person.id}:birth_edtf=${birthEdtf}`);
496
+ }
497
+ if (person.primary_place_id) {
498
+ leaks.push(`${mode}:person:${person.id}:primary_place_id`);
499
+ }
500
+ if (person.portrait_url || person.thumb_url) {
501
+ leaks.push(`${mode}:person:${person.id}:portrait`);
502
+ }
503
+ if (typeof person.media_count === 'number' && person.media_count > 0) {
504
+ leaks.push(`${mode}:person:${person.id}:media_count=${person.media_count}`);
505
+ }
506
+ }
507
+ const livingEventIds = new Set();
508
+ for (const ev of bundle.events) {
509
+ const hasLiving = ev.participants.some((pt) => livingIds.has(pt.person_id));
510
+ if (!hasLiving) {
511
+ continue;
512
+ }
513
+ livingEventIds.add(ev.id);
514
+ const edtfDate = ev.edtf_date.trim();
515
+ if (mode === 'private' && edtfDate.length > 0 && !YEAR_ONLY_RE.test(edtfDate)) {
516
+ leaks.push(`private:event:${ev.id}:edtf_date=${edtfDate}`);
517
+ }
518
+ if (ev.place_id) {
519
+ leaks.push(`${mode}:event:${ev.id}:place_id`);
520
+ }
521
+ if (ev.photo_url) {
522
+ leaks.push(`${mode}:event:${ev.id}:photo_url`);
523
+ }
524
+ }
525
+ for (const span of bundle.residence_spans) {
526
+ if (livingIds.has(span.person_id)) {
527
+ leaks.push(`${mode}:residence_span:${span.id}`);
528
+ }
529
+ }
530
+ for (const item of bundle.media ?? []) {
531
+ const linkedLiving = Boolean(item.person_id && livingIds.has(item.person_id)) ||
532
+ Boolean(item.person_ids?.some((pid) => livingIds.has(pid))) ||
533
+ Boolean(item.event_id && livingEventIds.has(item.event_id));
534
+ if (linkedLiving) {
535
+ leaks.push(`${mode}:media:${item.id}`);
536
+ }
537
+ }
538
+ for (const nar of bundle.narratives ?? []) {
539
+ if (nar.subject_person_id && livingIds.has(nar.subject_person_id)) {
540
+ leaks.push(`${mode}:narrative:${nar.id}:subject_person_id`);
541
+ }
542
+ if (nar.person_ids.some((pid) => livingIds.has(pid))) {
543
+ leaks.push(`${mode}:narrative:${nar.id}`);
544
+ }
545
+ }
546
+ return leaks;
547
+ }
548
+ function writeFileAtomic(filePath, content) {
549
+ const dir = path.dirname(filePath);
550
+ fs.mkdirSync(dir, { recursive: true });
551
+ const tmpPath = path.join(dir, `.${path.basename(filePath)}.tmp.${process.pid}.${Date.now()}`);
552
+ fs.writeFileSync(tmpPath, content, 'utf8');
553
+ fs.renameSync(tmpPath, filePath);
554
+ }
555
+ export async function runIntegrateCommand(options) {
556
+ const repoDir = path.resolve(options.repoDir?.trim() || process.cwd());
557
+ const personId = options.personId.trim();
558
+ const dryRun = Boolean(options.dryRun);
559
+ if (!personId) {
560
+ throw new CliValidationError('Missing required option `--person <person_id>`.');
561
+ }
562
+ if (!SAFE_PERSON_ID_RE.test(personId)) {
563
+ throw new CliValidationError(`Invalid person_id '${personId}'. Only ASCII letters, digits, _, and - are allowed.`);
564
+ }
565
+ if (!fs.existsSync(repoDir) || !fs.statSync(repoDir).isDirectory()) {
566
+ throw new CliValidationError(`Repository directory does not exist: ${repoDir}`);
567
+ }
568
+ const packageDir = path.resolve(options.packageDir?.trim() || path.join(repoDir, 'research', 'people', personId));
569
+ const dataDir = path.join(repoDir, 'data');
570
+ const configPath = path.join(repoDir, 'kinloom.config.yaml');
571
+ const patchPath = path.join(packageDir, 'patch.json');
572
+ if (!fs.existsSync(path.join(dataDir, 'people.yaml'))) {
573
+ throw new CliValidationError(`Missing ${path.join(dataDir, 'people.yaml')}.`);
574
+ }
575
+ if (!fs.existsSync(configPath)) {
576
+ throw new CliValidationError(`Missing ${configPath}.`);
577
+ }
578
+ if (!fs.existsSync(patchPath)) {
579
+ throw new CliValidationError(`Missing person patch file: ${patchPath}`);
580
+ }
581
+ const siteConfig = parseKinloomConfigYaml(fs.readFileSync(configPath, 'utf8'));
582
+ const rawPatch = JSON.parse(fs.readFileSync(patchPath, 'utf8'));
583
+ const patch = normalizeAndValidatePatch(rawPatch, personId);
584
+ const existingPeople = parsePeopleYaml(readOptionalUtf8(path.join(dataDir, 'people.yaml')));
585
+ const existingEvents = parseEventsYaml(readOptionalUtf8(path.join(dataDir, 'events.yaml')));
586
+ const existingPlaces = parsePlacesYaml(readOptionalUtf8(path.join(dataDir, 'places.yaml')));
587
+ const existingSources = parseSourcesYaml(readOptionalUtf8(path.join(dataDir, 'sources.yaml')));
588
+ const existingKinship = parseKinshipYaml(readOptionalUtf8(path.join(dataDir, 'kinship.yaml')));
589
+ const existingMedia = parseMediaYaml(readOptionalUtf8(path.join(dataDir, 'media.yaml')));
590
+ const existingNarratives = parseNarrativesYaml(readOptionalUtf8(path.join(dataDir, 'narratives.yaml')));
591
+ const enrichments = parseNarrativeEnrichmentsYaml(readOptionalUtf8(path.join(dataDir, 'narrative_enrichments.yaml')));
592
+ // Invariant 1: Target person must exist and must not be living.
593
+ const targetIdx = existingPeople.findIndex((p) => p.id === personId);
594
+ if (targetIdx === -1) {
595
+ throw new Error(`Target person '${personId}' does not exist in ${path.join(dataDir, 'people.yaml')}.`);
596
+ }
597
+ const targetPerson = existingPeople[targetIdx];
598
+ if (targetPerson.is_living || resolveEffectiveLiving(targetPerson, siteConfig.privacy)) {
599
+ throw new Error(`PRIVACY REFUSAL: Target person '${personId}' resolves as living. Living people cannot be researched or patched.`);
600
+ }
601
+ // Merge person_updates.
602
+ const mergedPeople = existingPeople.map((p) => structuredClone(p));
603
+ const personMerge = mergePersonUpdates(targetPerson, patch.person_updates, siteConfig.privacy);
604
+ mergedPeople[targetIdx] = personMerge.updated;
605
+ const peopleById = new Map(mergedPeople.map((p) => [p.id, p]));
606
+ const livingIds = new Set(mergedPeople
607
+ .filter((p) => p.is_living || resolveEffectiveLiving(p, siteConfig.privacy))
608
+ .map((p) => p.id));
609
+ // Invariant 2: Every place in patch.places and merged places must have valid non-(0, 0) coordinates.
610
+ const validatedPatchPlaces = patch.places.map((pl, idx) => PlaceSchema.parse(assertValidPlaceCoordinates(pl, `patch.places[${idx}]`)));
611
+ const placesMerge = upsertById(existingPlaces, validatedPatchPlaces, (p) => PlaceSchema.parse(p));
612
+ for (const pl of placesMerge.items) {
613
+ assertValidPlaceCoordinates(pl, `merged place '${pl.id}'`);
614
+ }
615
+ // Sources upsert + optional top-level source retirement.
616
+ const sourcesMerge = upsertById(existingSources, patch.sources, (s) => SourceRecordSchema.parse(s));
617
+ const topLevelRemoveSourceIds = new Set(patch.remove_source_ids);
618
+ if (topLevelRemoveSourceIds.size > 0) {
619
+ const patchedSourceIds = new Set(patch.sources.map((s) => SourceRecordSchema.parse(s).id));
620
+ for (const removeId of topLevelRemoveSourceIds) {
621
+ if (patchedSourceIds.has(removeId)) {
622
+ throw new Error(`patch.json cannot both add/update and remove source '${removeId}' in the same patch.`);
623
+ }
624
+ }
625
+ }
626
+ const removedSourceIds = [];
627
+ const finalSources = sourcesMerge.items.filter((src) => {
628
+ if (topLevelRemoveSourceIds.has(src.id)) {
629
+ removedSourceIds.push(src.id);
630
+ return false;
631
+ }
632
+ return true;
633
+ });
634
+ // Extract optional per-event remove_source_ids before schema parsing.
635
+ const eventRemoveSourceIds = new Map();
636
+ const cleanedPatchEvents = patch.events.map((rawEv, idx) => {
637
+ if (!isPlainObject(rawEv)) {
638
+ return rawEv;
639
+ }
640
+ const removeIds = parseOptionalStringList(rawEv.remove_source_ids, `patch.events[${idx}].remove_source_ids`);
641
+ const copy = { ...rawEv };
642
+ delete copy.remove_source_ids;
643
+ const parsedEv = RawEventSchema.parse(copy);
644
+ if (removeIds.length > 0) {
645
+ const removeSet = new Set(removeIds);
646
+ for (const ref of parsedEv.sources) {
647
+ if (removeSet.has(ref.source_id)) {
648
+ throw new Error(`Event '${parsedEv.id}' cannot both attach and remove source '${ref.source_id}'.`);
649
+ }
650
+ }
651
+ const existingSet = eventRemoveSourceIds.get(parsedEv.id);
652
+ if (existingSet) {
653
+ for (const id of removeSet) {
654
+ existingSet.add(id);
655
+ }
656
+ }
657
+ else {
658
+ eventRemoveSourceIds.set(parsedEv.id, removeSet);
659
+ }
660
+ }
661
+ return parsedEv;
662
+ });
663
+ // Events upsert preserving existing participants and sources on partial updates,
664
+ // while pruning any source IDs explicitly listed in remove_source_ids.
665
+ const eventsMerge = upsertById(existingEvents, cleanedPatchEvents, (ev) => RawEventSchema.parse(ev), (prev, incoming) => {
666
+ const toRemove = eventRemoveSourceIds.get(incoming.id);
667
+ const retainedPrevSources = toRemove
668
+ ? prev.sources.filter((ref) => !toRemove.has(ref.source_id))
669
+ : prev.sources;
670
+ return {
671
+ ...prev,
672
+ ...incoming,
673
+ participants: dedupeParticipants(prev.participants, incoming.participants),
674
+ sources: mergeEventSources(retainedPrevSources, incoming.sources),
675
+ };
676
+ });
677
+ const topLevelRemoveEventIds = new Set(patch.remove_event_ids);
678
+ if (topLevelRemoveEventIds.size > 0) {
679
+ const patchedEventIds = new Set(cleanedPatchEvents.map((ev) => RawEventSchema.parse(ev).id));
680
+ for (const removeId of topLevelRemoveEventIds) {
681
+ if (patchedEventIds.has(removeId)) {
682
+ throw new Error(`patch.json cannot both add/update and remove event '${removeId}' in the same patch.`);
683
+ }
684
+ }
685
+ }
686
+ const removedEventIds = [];
687
+ const finalEvents = eventsMerge.items.filter((ev) => {
688
+ if (topLevelRemoveEventIds.has(ev.id)) {
689
+ removedEventIds.push(ev.id);
690
+ return false;
691
+ }
692
+ return true;
693
+ });
694
+ // Media upsert + optional top-level media retirement.
695
+ const mediaMerge = upsertById(existingMedia, patch.media, (m) => MediaItemSchema.parse(m));
696
+ const topLevelRemoveMediaIds = new Set(patch.remove_media_ids);
697
+ if (topLevelRemoveMediaIds.size > 0) {
698
+ const patchedMediaIds = new Set(patch.media.map((m) => MediaItemSchema.parse(m).id));
699
+ for (const removeId of topLevelRemoveMediaIds) {
700
+ if (patchedMediaIds.has(removeId)) {
701
+ throw new Error(`patch.json cannot both add/update and remove media '${removeId}' in the same patch.`);
702
+ }
703
+ }
704
+ }
705
+ const removedMediaIds = [];
706
+ const finalMedia = mediaMerge.items.filter((item) => {
707
+ if (topLevelRemoveMediaIds.has(item.id)) {
708
+ removedMediaIds.push(item.id);
709
+ return false;
710
+ }
711
+ return true;
712
+ });
713
+ // Kinship upsert keyed by from|to|relation.
714
+ const kinshipMerge = upsertKinship(existingKinship, patch.kinship);
715
+ // Lookup sets before narrative normalization so inline citations are validated and auto-linked.
716
+ const placeIds = new Set(placesMerge.items.map((p) => p.id));
717
+ const sourceIds = new Set(finalSources.map((s) => s.id));
718
+ const mediaIds = new Set(finalMedia.map((m) => m.id));
719
+ const eventsById = new Map(finalEvents.map((e) => [e.id, e]));
720
+ let inlineCitationCount = 0;
721
+ const normalizedPatchNarratives = patch.narratives.map((rawNar) => {
722
+ if (!isPlainObject(rawNar)) {
723
+ return rawNar;
724
+ }
725
+ const copy = { ...rawNar };
726
+ if (copy.kind === undefined) {
727
+ copy.kind = 'biography';
728
+ }
729
+ if (copy.kind === 'biography' && copy.subject_person_id === undefined) {
730
+ copy.subject_person_id = personId;
731
+ }
732
+ if (typeof copy.body_md === 'string') {
733
+ const citationErrors = validateNarrativeCitations([{ id: typeof copy.id === 'string' ? copy.id : 'unknown', body_md: copy.body_md }], sourceIds, mediaIds);
734
+ if (citationErrors.length > 0) {
735
+ throw new Error(citationErrors[0]);
736
+ }
737
+ const extracted = extractNarrativeCitations(copy.body_md);
738
+ if (extracted.references.length > 0) {
739
+ const citedSourceIds = extracted.references.map((ref) => ref.sourceId);
740
+ copy.source_ids = dedupeStrings(Array.isArray(copy.source_ids)
741
+ ? copy.source_ids.filter((id) => typeof id === 'string')
742
+ : [], citedSourceIds);
743
+ }
744
+ inlineCitationCount += extracted.occurrences.length;
745
+ }
746
+ return copy;
747
+ });
748
+ const narrativesMerge = upsertById(existingNarratives, normalizedPatchNarratives, (n) => NarrativeSchema.parse(n));
749
+ // Referential integrity & privacy checks on patch additions/updates.
750
+ for (const rawEv of cleanedPatchEvents) {
751
+ const ev = RawEventSchema.parse(rawEv);
752
+ if (ev.place_id && !placeIds.has(ev.place_id)) {
753
+ throw new Error(`Event '${ev.id}' references missing place_id '${ev.place_id}'.`);
754
+ }
755
+ let touchesLiving = false;
756
+ for (const pt of ev.participants) {
757
+ if (!peopleById.has(pt.person_id)) {
758
+ throw new Error(`Event '${ev.id}' references missing person_id '${pt.person_id}'.`);
759
+ }
760
+ if (livingIds.has(pt.person_id)) {
761
+ touchesLiving = true;
762
+ }
763
+ }
764
+ if (touchesLiving) {
765
+ throw new Error(`PRIVACY REFUSAL: Patch event '${ev.id}' includes a living participant.`);
766
+ }
767
+ for (const ref of ev.sources) {
768
+ if (!sourceIds.has(ref.source_id)) {
769
+ throw new Error(`Event '${ev.id}' references missing source_id '${ref.source_id}'.`);
770
+ }
771
+ }
772
+ }
773
+ for (const rawEdge of patch.kinship) {
774
+ const edge = KinshipEdgeSchema.parse(rawEdge);
775
+ if (!peopleById.has(edge.from)) {
776
+ throw new Error(`Kinship edge references missing 'from' person '${edge.from}'.`);
777
+ }
778
+ if (!peopleById.has(edge.to)) {
779
+ throw new Error(`Kinship edge references missing 'to' person '${edge.to}'.`);
780
+ }
781
+ }
782
+ for (const rawNar of normalizedPatchNarratives) {
783
+ const nar = NarrativeSchema.parse(rawNar);
784
+ if (nar.subject_person_id !== undefined) {
785
+ if (!peopleById.has(nar.subject_person_id)) {
786
+ throw new Error(`Narrative '${nar.id}' references missing subject_person_id '${nar.subject_person_id}'.`);
787
+ }
788
+ if (livingIds.has(nar.subject_person_id)) {
789
+ throw new Error(`PRIVACY REFUSAL: Narrative '${nar.id}' references living subject_person_id '${nar.subject_person_id}'.`);
790
+ }
791
+ }
792
+ for (const pid of nar.person_ids) {
793
+ if (!peopleById.has(pid)) {
794
+ throw new Error(`Narrative '${nar.id}' references missing person_id '${pid}'.`);
795
+ }
796
+ if (livingIds.has(pid)) {
797
+ throw new Error(`PRIVACY REFUSAL: Narrative '${nar.id}' references living person '${pid}'.`);
798
+ }
799
+ }
800
+ for (const plId of nar.place_ids) {
801
+ if (!placeIds.has(plId)) {
802
+ throw new Error(`Narrative '${nar.id}' references missing place_id '${plId}'.`);
803
+ }
804
+ }
805
+ for (const evId of nar.event_ids) {
806
+ if (!eventsById.has(evId)) {
807
+ throw new Error(`Narrative '${nar.id}' references missing event_id '${evId}'.`);
808
+ }
809
+ }
810
+ for (const srcId of nar.source_ids) {
811
+ if (!sourceIds.has(srcId)) {
812
+ throw new Error(`Narrative '${nar.id}' references missing source_id '${srcId}'.`);
813
+ }
814
+ }
815
+ }
816
+ // Ensure top-level event removal never leaves dangling references in surviving media or narratives.
817
+ if (topLevelRemoveEventIds.size > 0) {
818
+ for (const item of finalMedia) {
819
+ if (item.event_id && topLevelRemoveEventIds.has(item.event_id)) {
820
+ throw new Error(`Cannot remove event '${item.event_id}': media '${item.id}' still references it.`);
821
+ }
822
+ }
823
+ for (const nar of narrativesMerge.items) {
824
+ for (const evId of nar.event_ids) {
825
+ if (topLevelRemoveEventIds.has(evId)) {
826
+ throw new Error(`Cannot remove event '${evId}': narrative '${nar.id}' still references it in event_ids.`);
827
+ }
828
+ }
829
+ }
830
+ }
831
+ // Ensure top-level media removal never breaks surviving narrative inline citations.
832
+ if (topLevelRemoveMediaIds.size > 0) {
833
+ for (const nar of narrativesMerge.items) {
834
+ const extracted = extractNarrativeCitations(nar.body_md);
835
+ for (const occ of extracted.occurrences) {
836
+ if (occ.mediaId && topLevelRemoveMediaIds.has(occ.mediaId)) {
837
+ throw new Error(`Cannot remove media '${occ.mediaId}': narrative '${nar.id}' still cites it inline.`);
838
+ }
839
+ }
840
+ }
841
+ }
842
+ // Ensure top-level source removal never breaks citations or references anywhere in the archive.
843
+ if (topLevelRemoveSourceIds.size > 0) {
844
+ for (const ev of finalEvents) {
845
+ for (const ref of ev.sources) {
846
+ if (topLevelRemoveSourceIds.has(ref.source_id)) {
847
+ throw new Error(`Cannot remove source '${ref.source_id}': event '${ev.id}' still cites it.`);
848
+ }
849
+ }
850
+ }
851
+ for (const item of finalMedia) {
852
+ if (item.source_id && topLevelRemoveSourceIds.has(item.source_id)) {
853
+ throw new Error(`Cannot remove source '${item.source_id}': media '${item.id}' still references it.`);
854
+ }
855
+ }
856
+ for (const nar of narrativesMerge.items) {
857
+ for (const srcId of nar.source_ids) {
858
+ if (topLevelRemoveSourceIds.has(srcId)) {
859
+ throw new Error(`Cannot remove source '${srcId}': narrative '${nar.id}' still lists it in source_ids.`);
860
+ }
861
+ }
862
+ }
863
+ const allCitationErrors = validateNarrativeCitations(narrativesMerge.items, sourceIds, mediaIds);
864
+ if (allCitationErrors.length > 0) {
865
+ throw new Error(allCitationErrors[0]);
866
+ }
867
+ for (const person of mergedPeople) {
868
+ const extSources = isPlainObject(person.extensions) && Array.isArray(person.extensions.sources)
869
+ ? person.extensions.sources
870
+ : [];
871
+ for (const entry of extSources) {
872
+ const refId = typeof entry === 'string'
873
+ ? entry.trim()
874
+ : isPlainObject(entry) && typeof entry.source_id === 'string'
875
+ ? entry.source_id
876
+ : null;
877
+ if (refId && topLevelRemoveSourceIds.has(refId)) {
878
+ throw new Error(`Cannot remove source '${refId}': person '${person.id}' still cites it in extensions.sources.`);
879
+ }
880
+ }
881
+ }
882
+ }
883
+ // Scan staging plan & verify every patch.media[].file exists on disk or in packageDir/scans/.
884
+ const mediaLayout = detectMediaLayout(repoDir);
885
+ const plannedScans = planScanStaging(repoDir, packageDir, mediaLayout);
886
+ const stagedDestSet = new Set(plannedScans.map((s) => s.destPath));
887
+ for (const rawMedia of patch.media) {
888
+ const item = MediaItemSchema.parse(rawMedia);
889
+ const privacyCheck = validateMediaForPrivacy(item, livingIds, eventsById);
890
+ if (!privacyCheck.ok) {
891
+ throw new Error(`PRIVACY REFUSAL: ${privacyCheck.message}`);
892
+ }
893
+ for (const pid of getMediaPersonIds(item)) {
894
+ if (!peopleById.has(pid)) {
895
+ throw new Error(`Media '${item.id}' references missing person_id '${pid}'.`);
896
+ }
897
+ }
898
+ if (item.event_id && !eventsById.has(item.event_id)) {
899
+ throw new Error(`Media '${item.id}' references missing event_id '${item.event_id}'.`);
900
+ }
901
+ if (item.source_id && !sourceIds.has(item.source_id)) {
902
+ throw new Error(`Media '${item.id}' references missing source_id '${item.source_id}'.`);
903
+ }
904
+ const expectedDiskPath = resolveMediaDiskPath(item.file, repoDir, mediaLayout);
905
+ if (!fs.existsSync(expectedDiskPath) && !stagedDestSet.has(expectedDiskPath)) {
906
+ throw new Error(`Missing scan file for media '${item.id}': '${item.file}' expected at '${expectedDiskPath}' (not on disk and not staged from ${path.join(packageDir, 'scans')}).`);
907
+ }
908
+ }
909
+ // Compile merged archive in both private and public modes before writing anything.
910
+ const compileBase = {
911
+ people: mergedPeople,
912
+ events: finalEvents,
913
+ places: placesMerge.items,
914
+ sources: finalSources,
915
+ kinship: kinshipMerge.items,
916
+ media: finalMedia,
917
+ narratives: narrativesMerge.items,
918
+ ...(enrichments.length > 0 ? { enrichments } : {}),
919
+ siteConfig,
920
+ };
921
+ const privateResult = compileArchive({ ...compileBase, mode: 'private' });
922
+ const publicResult = compileArchive({ ...compileBase, mode: 'public' });
923
+ ArchiveBundleSchema.parse(privateResult.bundle);
924
+ ArchiveBundleSchema.parse(publicResult.bundle);
925
+ const privateLeaks = auditBundlePrivacy(privateResult.bundle, 'private');
926
+ const publicLeaks = auditBundlePrivacy(publicResult.bundle, 'public');
927
+ const allLeaks = [...privateLeaks, ...publicLeaks];
928
+ if (allLeaks.length > 0) {
929
+ throw new Error(`PRIVACY LEAK DETECTED (${allLeaks.length}): ${allLeaks.join('; ')}`);
930
+ }
931
+ if (privateResult.reviewFlags.length > 0 || publicResult.reviewFlags.length > 0) {
932
+ throw new Error(`PRIVACY REVIEW FLAGS DETECTED (private=${privateResult.reviewFlags.length}, public=${publicResult.reviewFlags.length}): ${[
933
+ ...privateResult.reviewFlags,
934
+ ...publicResult.reviewFlags,
935
+ ].join('; ')}`);
936
+ }
937
+ // Stage scans and write modified YAML files when not dryRun.
938
+ const stagedScansReport = [];
939
+ for (const scan of plannedScans) {
940
+ let status;
941
+ if (dryRun) {
942
+ status = scan.alreadyIdentical ? 'unchanged' : 'would_stage';
943
+ }
944
+ else if (scan.alreadyIdentical) {
945
+ status = 'unchanged';
946
+ }
947
+ else {
948
+ fs.mkdirSync(path.dirname(scan.destPath), { recursive: true });
949
+ fs.copyFileSync(scan.sourcePath, scan.destPath);
950
+ status = 'staged';
951
+ }
952
+ stagedScansReport.push({
953
+ filename: scan.filename,
954
+ sourcePath: scan.sourcePath,
955
+ destPath: scan.destPath,
956
+ url: scan.url,
957
+ r2Key: scan.r2Key,
958
+ status,
959
+ sizeBytes: scan.sizeBytes,
960
+ sha256: scan.sha256,
961
+ });
962
+ }
963
+ const pendingWrites = [];
964
+ if (personMerge.changed) {
965
+ pendingWrites.push({
966
+ file: 'people.yaml',
967
+ content: serializePeopleYaml(mergedPeople, { sortById: true }),
968
+ });
969
+ }
970
+ if (eventsMerge.counts.added > 0 || eventsMerge.counts.updated > 0 || removedEventIds.length > 0) {
971
+ pendingWrites.push({
972
+ file: 'events.yaml',
973
+ content: serializeEventsYaml(finalEvents, { sortById: true }),
974
+ });
975
+ }
976
+ if (placesMerge.counts.added > 0 || placesMerge.counts.updated > 0) {
977
+ pendingWrites.push({
978
+ file: 'places.yaml',
979
+ content: serializePlacesYaml(placesMerge.items, { sortById: true }),
980
+ });
981
+ }
982
+ if (sourcesMerge.counts.added > 0 || sourcesMerge.counts.updated > 0 || removedSourceIds.length > 0) {
983
+ pendingWrites.push({
984
+ file: 'sources.yaml',
985
+ content: serializeSourcesYaml(finalSources, { sortById: true }),
986
+ });
987
+ }
988
+ if (kinshipMerge.counts.added > 0 || kinshipMerge.counts.updated > 0) {
989
+ pendingWrites.push({
990
+ file: 'kinship.yaml',
991
+ content: serializeKinshipYaml(kinshipMerge.items, { sortDeterministic: true }),
992
+ });
993
+ }
994
+ if (mediaMerge.counts.added > 0 || mediaMerge.counts.updated > 0 || removedMediaIds.length > 0) {
995
+ pendingWrites.push({
996
+ file: 'media.yaml',
997
+ content: serializeMediaYaml(finalMedia, { sortById: true }),
998
+ });
999
+ }
1000
+ if (narrativesMerge.counts.added > 0 || narrativesMerge.counts.updated > 0) {
1001
+ pendingWrites.push({
1002
+ file: 'narratives.yaml',
1003
+ content: serializeNarrativesYaml(narrativesMerge.items, { sortById: true }),
1004
+ });
1005
+ }
1006
+ const writtenYamlFiles = [];
1007
+ if (!dryRun) {
1008
+ for (const item of pendingWrites) {
1009
+ const fullPath = path.join(dataDir, item.file);
1010
+ writeFileAtomic(fullPath, item.content);
1011
+ writtenYamlFiles.push(fullPath);
1012
+ }
1013
+ }
1014
+ const summaryBase = {
1015
+ ok: true,
1016
+ dryRun,
1017
+ repo: repoDir,
1018
+ personId,
1019
+ packageDir,
1020
+ mediaLayout: mediaLayout.layout,
1021
+ counts: {
1022
+ personUpdated: personMerge.changed,
1023
+ events: eventsMerge.counts,
1024
+ places: placesMerge.counts,
1025
+ sources: sourcesMerge.counts,
1026
+ media: mediaMerge.counts,
1027
+ kinship: kinshipMerge.counts,
1028
+ narratives: narrativesMerge.counts,
1029
+ },
1030
+ removedSourceIds,
1031
+ removedEventIds,
1032
+ removedMediaIds,
1033
+ removedEvents: removedEventIds.length,
1034
+ removedMedia: removedMediaIds.length,
1035
+ inlineCitationCount,
1036
+ stagedScans: stagedScansReport,
1037
+ wouldWriteYamlFiles: pendingWrites.map((w) => path.join(dataDir, w.file)),
1038
+ writtenYamlFiles,
1039
+ validation: {
1040
+ privateCounts: privateResult.bundle.meta.counts,
1041
+ publicCounts: publicResult.bundle.meta.counts,
1042
+ privateReviewFlags: privateResult.reviewFlags.length,
1043
+ publicReviewFlags: publicResult.reviewFlags.length,
1044
+ livingLeaks: allLeaks.length,
1045
+ },
1046
+ };
1047
+ const rendered = options.json
1048
+ ? JSON.stringify(summaryBase, null, 2)
1049
+ : `Integrate ${dryRun ? 'dry-run ' : ''}OK for ${personId}: ` +
1050
+ `person=${personMerge.changed ? 'updated' : 'unchanged'}, ` +
1051
+ `events=+${eventsMerge.counts.added}/~${eventsMerge.counts.updated}${removedEventIds.length > 0 ? `/-${removedEventIds.length}` : ''}, ` +
1052
+ `places=+${placesMerge.counts.added}/~${placesMerge.counts.updated}, ` +
1053
+ `sources=+${sourcesMerge.counts.added}/~${sourcesMerge.counts.updated}${removedSourceIds.length > 0 ? `/-${removedSourceIds.length}` : ''}, ` +
1054
+ `media=+${mediaMerge.counts.added}/~${mediaMerge.counts.updated}${removedMediaIds.length > 0 ? `/-${removedMediaIds.length}` : ''}, ` +
1055
+ `narratives=+${narrativesMerge.counts.added}/~${narrativesMerge.counts.updated}, ` +
1056
+ `inlineCitations=${inlineCitationCount}, scans=${stagedScansReport.length}, ` +
1057
+ `written=${writtenYamlFiles.length}`;
1058
+ return {
1059
+ ...summaryBase,
1060
+ rendered,
1061
+ };
1062
+ }
1063
+ //# sourceMappingURL=integrate.js.map