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