@kinloom/cli 0.1.1 → 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/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,867 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
import { parseKinloomConfigYaml, resolveEffectiveLiving, } from '@kinloom/core';
|
|
6
|
+
import { CliValidationError } from '../../errors.js';
|
|
7
|
+
import { extractYamlBlockId, parseMatchingYamlBlocks, splitTopLevelYamlList, } from './context.js';
|
|
8
|
+
import { runIntegrateCommand } from './integrate.js';
|
|
9
|
+
const SAFE_PERSON_ID_RE = /^[a-zA-Z0-9_-]+$/;
|
|
10
|
+
const SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
|
|
11
|
+
const US_PHONE_RE = /(?<!\d)(?:\+1[-.\s]?)?(?:\(\d{3}\)[-.\s]?|\b[2-9]\d{2}[-.\s])[2-9]\d{2}[-.\s]\d{4}(?!\d)/g;
|
|
12
|
+
const EM_DASH_RE = /\u2014/g;
|
|
13
|
+
const INLINE_CITATION_RE = /\[\^src_[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?\]/;
|
|
14
|
+
const POST_MORTEM_RE = /\b(burial|buried|funeral|probate|will|estate|obituary|memorial|gravestone|headstone|cemetery|cenotaph|interment|interred|administration|inventory|tombstone|inquest|posthumous|heirs?|executors?|widow)\b/i;
|
|
15
|
+
const PRE_BIRTH_CONTEXT_RE = /\b(father|mother|parents?|ancestors?|pre-birth|prior to birth|before birth|family origin)\b/i;
|
|
16
|
+
const CENSUS_RE = /\b(census|enumerat\w*)\b/i;
|
|
17
|
+
const MARRIAGE_RE = /\b(marr(?:iage|ied)?|wedding|nuptial)\b/i;
|
|
18
|
+
const SPOUSE_ROLE_RE = /\b(spouse|bride|groom|husband|wife|principal|subject|partner)\b/i;
|
|
19
|
+
const MIN_SCAN_WARN_BYTES = 10 * 1024;
|
|
20
|
+
const MAX_SCAN_WARN_BYTES = 10 * 1024 * 1024;
|
|
21
|
+
const ABBREVIATIONS = [
|
|
22
|
+
'Mr.', 'Mrs.', 'Ms.', 'Dr.', 'Capt.', 'Col.', 'Lt.', 'Gen.', 'Sgt.', 'Cpl.', 'Pvt.',
|
|
23
|
+
'Rev.', 'Hon.', 'St.', 'Jr.', 'Sr.', 'Prof.', 'Gov.', 'Pres.', 'Vol.', 'Vols.',
|
|
24
|
+
'No.', 'Nos.', 'Lib.', 'Fol.', 'Fols.', 'fol.', 'fols.', 'Ch.', 'Sec.', 'Fig.',
|
|
25
|
+
'Ed.', 'Eds.', 'p.', 'pp.', 'c.', 'ca.', 'cf.', 'e.g.', 'i.e.', 'et al.', 'etc.',
|
|
26
|
+
'vs.', 'v.', 'viz.',
|
|
27
|
+
'Jan.', 'Feb.', 'Mar.', 'Apr.', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Sept.', 'Oct.', 'Nov.', 'Dec.',
|
|
28
|
+
'JAN.', 'FEB.', 'MAR.', 'APR.', 'JUN.', 'JUL.', 'AUG.', 'SEP.', 'SEPT.', 'OCT.', 'NOV.', 'DEC.',
|
|
29
|
+
'U.S.', 'U.S.A.', 'N.J.', 'N.Y.', 'Pa.', 'Va.', 'Md.', 'Mass.', 'Conn.', 'Calif.',
|
|
30
|
+
'Ind.', 'Ill.', 'Mo.', 'Ky.', 'Tenn.', 'N.C.', 'S.C.', 'Inc.', 'Co.', 'Ltd.',
|
|
31
|
+
'B.C.', 'A.D.', 'a.m.', 'p.m.', 'b.', 'd.', 'm.', 'bur.', 'bap.', 'chr.',
|
|
32
|
+
];
|
|
33
|
+
export { AUDIT_HELP } from './help.js';
|
|
34
|
+
function isPlainRecord(value) {
|
|
35
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
function asString(value) {
|
|
38
|
+
if (value === null || value === undefined) {
|
|
39
|
+
return '';
|
|
40
|
+
}
|
|
41
|
+
return String(value);
|
|
42
|
+
}
|
|
43
|
+
export function parseAuditEdtf(raw) {
|
|
44
|
+
if (typeof raw !== 'string') {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const trimmed = raw.trim();
|
|
48
|
+
if (!trimmed) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const primary = trimmed.includes('/') ? trimmed.split('/')[0].trim() : trimmed;
|
|
52
|
+
const approximate = /[~?%]/.test(trimmed);
|
|
53
|
+
const clean = primary.replaceAll(/[~?%]/g, '');
|
|
54
|
+
const full = /^(\d{4})-(\d{2})-(\d{2})$/.exec(clean);
|
|
55
|
+
if (full) {
|
|
56
|
+
const year = Number(full[1]);
|
|
57
|
+
const month = Number(full[2]);
|
|
58
|
+
const day = Number(full[3]);
|
|
59
|
+
const ms = Date.UTC(year, month - 1, day);
|
|
60
|
+
return {
|
|
61
|
+
raw: trimmed,
|
|
62
|
+
year,
|
|
63
|
+
month,
|
|
64
|
+
day,
|
|
65
|
+
precision: 'day',
|
|
66
|
+
approximate,
|
|
67
|
+
startMs: ms,
|
|
68
|
+
endMs: ms,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const ym = /^(\d{4})-(\d{2})$/.exec(clean);
|
|
72
|
+
if (ym) {
|
|
73
|
+
const year = Number(ym[1]);
|
|
74
|
+
const month = Number(ym[2]);
|
|
75
|
+
const startMs = Date.UTC(year, month - 1, 1);
|
|
76
|
+
const endMs = Date.UTC(year, month, 0);
|
|
77
|
+
return {
|
|
78
|
+
raw: trimmed,
|
|
79
|
+
year,
|
|
80
|
+
month,
|
|
81
|
+
day: null,
|
|
82
|
+
precision: 'month',
|
|
83
|
+
approximate,
|
|
84
|
+
startMs,
|
|
85
|
+
endMs,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const y = /^(\d{4})/.exec(clean);
|
|
89
|
+
if (y) {
|
|
90
|
+
const year = Number(y[1]);
|
|
91
|
+
return {
|
|
92
|
+
raw: trimmed,
|
|
93
|
+
year,
|
|
94
|
+
month: null,
|
|
95
|
+
day: null,
|
|
96
|
+
precision: 'year',
|
|
97
|
+
approximate,
|
|
98
|
+
startMs: Date.UTC(year, 0, 1),
|
|
99
|
+
endMs: Date.UTC(year, 11, 31),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
export function computeLifespan(birth, death) {
|
|
105
|
+
if (!birth || !death) {
|
|
106
|
+
return { exact: false, years: null, days: null, totalDays: null, label: null };
|
|
107
|
+
}
|
|
108
|
+
if (birth.precision === 'day' &&
|
|
109
|
+
death.precision === 'day' &&
|
|
110
|
+
birth.month !== null &&
|
|
111
|
+
birth.day !== null) {
|
|
112
|
+
const totalDays = Math.round((death.startMs - birth.startMs) / 86_400_000);
|
|
113
|
+
let years = death.year - birth.year;
|
|
114
|
+
let anniversary = Date.UTC(birth.year + years, birth.month - 1, birth.day);
|
|
115
|
+
if (anniversary > death.startMs) {
|
|
116
|
+
years -= 1;
|
|
117
|
+
anniversary = Date.UTC(birth.year + years, birth.month - 1, birth.day);
|
|
118
|
+
}
|
|
119
|
+
const remDays = Math.round((death.startMs - anniversary) / 86_400_000);
|
|
120
|
+
return {
|
|
121
|
+
exact: true,
|
|
122
|
+
years,
|
|
123
|
+
days: remDays,
|
|
124
|
+
totalDays,
|
|
125
|
+
label: `${years} years, ${remDays} days (${totalDays} days)`,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
const approxYears = death.year - birth.year;
|
|
129
|
+
return {
|
|
130
|
+
exact: false,
|
|
131
|
+
years: approxYears,
|
|
132
|
+
days: null,
|
|
133
|
+
totalDays: null,
|
|
134
|
+
label: `~${approxYears} years`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export function runChronologyCheck(targetPerson, patch, existingPersonEvents) {
|
|
138
|
+
const updates = isPlainRecord(patch.person_updates) ? patch.person_updates : {};
|
|
139
|
+
const birthRaw = updates.birth_edtf ?? updates.birth_date ?? targetPerson?.birth_edtf ?? '';
|
|
140
|
+
const deathRaw = updates.death_edtf ?? updates.death_date ?? targetPerson?.death_edtf ?? '';
|
|
141
|
+
const birth = parseAuditEdtf(asString(birthRaw));
|
|
142
|
+
const death = parseAuditEdtf(asString(deathRaw));
|
|
143
|
+
const lifespan = computeLifespan(birth, death);
|
|
144
|
+
const errors = [];
|
|
145
|
+
const warnings = [];
|
|
146
|
+
if (birth && death && birth.startMs > death.endMs) {
|
|
147
|
+
errors.push(`Birth (${birth.raw}) is after death (${death.raw}).`);
|
|
148
|
+
}
|
|
149
|
+
if (lifespan.years !== null && (lifespan.years < 0 || lifespan.years > 118)) {
|
|
150
|
+
errors.push(`Implausible lifespan: ${lifespan.label} (${birth?.raw} to ${death?.raw}).`);
|
|
151
|
+
}
|
|
152
|
+
const eventMap = new Map();
|
|
153
|
+
for (const ev of existingPersonEvents) {
|
|
154
|
+
if (typeof ev.id === 'string' && ev.id) {
|
|
155
|
+
eventMap.set(ev.id, ev);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
for (const rawEv of Array.isArray(patch.events) ? patch.events : []) {
|
|
159
|
+
if (isPlainRecord(rawEv) && typeof rawEv.id === 'string' && rawEv.id) {
|
|
160
|
+
eventMap.set(rawEv.id, rawEv);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const personId = typeof patch.person_id === 'string' ? patch.person_id : '';
|
|
164
|
+
let checkedEvents = 0;
|
|
165
|
+
for (const ev of eventMap.values()) {
|
|
166
|
+
const dt = parseAuditEdtf(asString(ev.edtf_date));
|
|
167
|
+
if (!dt) {
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
checkedEvents += 1;
|
|
171
|
+
const evId = asString(ev.id);
|
|
172
|
+
const textBlob = `${evId} ${asString(ev.event_kind)} ${asString(ev.title)} ${asString(ev.summary)}`;
|
|
173
|
+
const isPostMortemAllowed = POST_MORTEM_RE.test(textBlob);
|
|
174
|
+
const isPreBirthContext = PRE_BIRTH_CONTEXT_RE.test(textBlob);
|
|
175
|
+
const isCensus = CENSUS_RE.test(`${evId} ${asString(ev.title)}`);
|
|
176
|
+
const isMarriage = MARRIAGE_RE.test(`${evId} ${asString(ev.event_kind)} ${asString(ev.title)}`);
|
|
177
|
+
const birthMinMs = birth
|
|
178
|
+
? birth.approximate
|
|
179
|
+
? Date.UTC(birth.year - 1, 0, 1)
|
|
180
|
+
: birth.startMs
|
|
181
|
+
: null;
|
|
182
|
+
const deathMaxMs = death
|
|
183
|
+
? death.approximate
|
|
184
|
+
? Date.UTC(death.year + 1, 11, 31)
|
|
185
|
+
: death.endMs
|
|
186
|
+
: null;
|
|
187
|
+
if (birth && birthMinMs !== null && dt.endMs < birthMinMs) {
|
|
188
|
+
if (isCensus) {
|
|
189
|
+
if (!isPreBirthContext) {
|
|
190
|
+
errors.push(`Event ${evId} (${dt.raw}): census predates birth (${birth.raw}) without context label.`);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
warnings.push(`Event ${evId} (${dt.raw}): labeled pre-birth census context before birth (${birth.raw}).`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
else if (isPreBirthContext) {
|
|
197
|
+
warnings.push(`Event ${evId} (${dt.raw}): pre-birth family context before birth (${birth.raw}).`);
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
errors.push(`Event ${evId} (${dt.raw}): predates birth (${birth.raw}).`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (death && deathMaxMs !== null && dt.startMs > deathMaxMs) {
|
|
204
|
+
if (isCensus) {
|
|
205
|
+
if (!isPostMortemAllowed) {
|
|
206
|
+
errors.push(`Event ${evId} (${dt.raw}): census postdates death (${death.raw}) without explicit posthumous/widow label.`);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
warnings.push(`Event ${evId} (${dt.raw}): labeled post-mortem census entry after death (${death.raw}).`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
else if (!isPostMortemAllowed) {
|
|
213
|
+
errors.push(`Event ${evId} (${dt.raw}): postdates death (${death.raw}) and is not a burial/probate/obituary/memorial event.`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (birth && isMarriage) {
|
|
217
|
+
const participants = Array.isArray(ev.participants) ? ev.participants : [];
|
|
218
|
+
const subjectPart = participants.find((pt) => isPlainRecord(pt) && pt.person_id === personId);
|
|
219
|
+
const role = isPlainRecord(subjectPart) ? asString(subjectPart.role) : '';
|
|
220
|
+
const isPrincipalSpouse = !role || SPOUSE_ROLE_RE.test(role);
|
|
221
|
+
if (isPrincipalSpouse) {
|
|
222
|
+
const beforeBirthday = birth.precision === 'day' &&
|
|
223
|
+
dt.precision === 'day' &&
|
|
224
|
+
birth.month !== null &&
|
|
225
|
+
birth.day !== null &&
|
|
226
|
+
dt.month !== null &&
|
|
227
|
+
dt.day !== null &&
|
|
228
|
+
(dt.month < birth.month || (dt.month === birth.month && dt.day < birth.day));
|
|
229
|
+
const ageAtEvent = dt.year - birth.year - (beforeBirthday ? 1 : 0);
|
|
230
|
+
if (ageAtEvent < 12) {
|
|
231
|
+
errors.push(`Event ${evId} (${dt.raw}): marriage at implausible age ${ageAtEvent} (birth ${birth.raw}).`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
ok: errors.length === 0,
|
|
238
|
+
birth_edtf: birth?.raw ?? null,
|
|
239
|
+
death_edtf: death?.raw ?? null,
|
|
240
|
+
lifespan,
|
|
241
|
+
checkedEvents,
|
|
242
|
+
errors,
|
|
243
|
+
warnings,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function collectStringsWithPath(value, prefix, out) {
|
|
247
|
+
if (typeof value === 'string') {
|
|
248
|
+
out.push({ path: prefix, text: value });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (Array.isArray(value)) {
|
|
252
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
253
|
+
collectStringsWithPath(value[i], `${prefix}[${i}]`, out);
|
|
254
|
+
}
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (isPlainRecord(value)) {
|
|
258
|
+
for (const [k, v] of Object.entries(value)) {
|
|
259
|
+
collectStringsWithPath(v, prefix ? `${prefix}.${k}` : k, out);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function compileAuditLivingNameRegex(livingPeople) {
|
|
264
|
+
const names = new Set();
|
|
265
|
+
for (const p of livingPeople) {
|
|
266
|
+
const alts = Array.isArray(p.alt_names) ? p.alt_names : [];
|
|
267
|
+
for (const raw of [p.full_name, ...alts]) {
|
|
268
|
+
if (typeof raw !== 'string') {
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const cleaned = raw.trim();
|
|
272
|
+
// Multi-word names >= 6 chars prevent common single-token false positives.
|
|
273
|
+
if (cleaned.length >= 6 && cleaned.includes(' ')) {
|
|
274
|
+
names.add(cleaned);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (names.size === 0) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
const escaped = [...names]
|
|
282
|
+
.toSorted((a, b) => b.length - a.length)
|
|
283
|
+
.map((n) => n.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
284
|
+
return new RegExp(`(?<![A-Za-z])(?:${escaped.join('|')})(?![A-Za-z])`, 'gi');
|
|
285
|
+
}
|
|
286
|
+
export function runPrivacyAndStyleScan(dossierText, patch, livingPeople) {
|
|
287
|
+
const livingNameRegex = compileAuditLivingNameRegex(livingPeople);
|
|
288
|
+
const livingNameHits = [];
|
|
289
|
+
const ssnHits = [];
|
|
290
|
+
const phoneHits = [];
|
|
291
|
+
const emDashHits = [];
|
|
292
|
+
const scanTarget = (label, text, checkEmDash) => {
|
|
293
|
+
if (!text) {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (livingNameRegex) {
|
|
297
|
+
for (const m of text.matchAll(livingNameRegex)) {
|
|
298
|
+
if (livingNameHits.length < 50) {
|
|
299
|
+
livingNameHits.push({ location: label, match: m[0] });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
for (const m of text.matchAll(SSN_RE)) {
|
|
304
|
+
if (ssnHits.length < 25) {
|
|
305
|
+
ssnHits.push({ location: label, match: m[0] });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
for (const m of text.matchAll(US_PHONE_RE)) {
|
|
309
|
+
if (phoneHits.length < 25) {
|
|
310
|
+
phoneHits.push({ location: label, match: m[0] });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (checkEmDash) {
|
|
314
|
+
const count = (text.match(EM_DASH_RE) ?? []).length;
|
|
315
|
+
if (count > 0) {
|
|
316
|
+
emDashHits.push({ location: label, count });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
if (dossierText) {
|
|
321
|
+
scanTarget('dossier.md', dossierText, true);
|
|
322
|
+
}
|
|
323
|
+
const patchStrings = [];
|
|
324
|
+
collectStringsWithPath(patch, 'patch', patchStrings);
|
|
325
|
+
for (const item of patchStrings) {
|
|
326
|
+
const isBioProse = item.path.endsWith('.body_md') ||
|
|
327
|
+
item.path.endsWith('.biography') ||
|
|
328
|
+
item.path.endsWith('.bio');
|
|
329
|
+
scanTarget(item.path, item.text, isBioProse);
|
|
330
|
+
}
|
|
331
|
+
const totalEmDashes = emDashHits.reduce((acc, row) => acc + row.count, 0);
|
|
332
|
+
const errors = [];
|
|
333
|
+
const warnings = [];
|
|
334
|
+
if (livingNameHits.length > 0) {
|
|
335
|
+
errors.push(`Found ${livingNameHits.length} living-relative name mention(s).`);
|
|
336
|
+
}
|
|
337
|
+
if (ssnHits.length > 0) {
|
|
338
|
+
errors.push(`Found ${ssnHits.length} SSN-like pattern(s).`);
|
|
339
|
+
}
|
|
340
|
+
if (phoneHits.length > 0) {
|
|
341
|
+
errors.push(`Found ${phoneHits.length} US phone-number pattern(s).`);
|
|
342
|
+
}
|
|
343
|
+
if (totalEmDashes > 0) {
|
|
344
|
+
warnings.push(`Found ${totalEmDashes} em-dash character(s) in biography prose.`);
|
|
345
|
+
}
|
|
346
|
+
return {
|
|
347
|
+
ok: errors.length === 0,
|
|
348
|
+
livingPeopleChecked: livingPeople.length,
|
|
349
|
+
livingNameHits,
|
|
350
|
+
ssnHits,
|
|
351
|
+
phoneHits,
|
|
352
|
+
emDashCount: totalEmDashes,
|
|
353
|
+
emDashHits,
|
|
354
|
+
errors,
|
|
355
|
+
warnings,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
export function splitParagraphIntoSentences(paragraph) {
|
|
359
|
+
let protectedText = paragraph.replaceAll(/\s+/g, ' ').trim();
|
|
360
|
+
if (!protectedText) {
|
|
361
|
+
return [];
|
|
362
|
+
}
|
|
363
|
+
// Mask punctuation inside inline code spans (e.g. gravestone text `AUG. 29, 1926`).
|
|
364
|
+
protectedText = protectedText.replaceAll(/`[^`]+`/g, (m) => m.replaceAll('.', '\u0001').replaceAll('!', '\u0002').replaceAll('?', '\u0003'));
|
|
365
|
+
// Mask common abbreviations and single-letter initials (e.g. "C. P. and Emma Alder").
|
|
366
|
+
for (const abbr of ABBREVIATIONS) {
|
|
367
|
+
const escaped = abbr.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
368
|
+
const re = new RegExp(`(?<![A-Za-z])${escaped}`, 'g');
|
|
369
|
+
protectedText = protectedText.replaceAll(re, (m) => m.replaceAll('.', '\u0001'));
|
|
370
|
+
}
|
|
371
|
+
protectedText = protectedText.replaceAll(/(?<![A-Za-z])([A-Z])\.(?=\s+[A-Za-z&(])/g, '$1\u0001');
|
|
372
|
+
// Keep inline citation tokens attached to the preceding sentence punctuation.
|
|
373
|
+
const rawParts = protectedText.split(/(?<=[.!?]["”’')]*?(?:\[\^[^\]]+\])*)\s+(?=[A-Z0-9"“‘'([]|[^a-z\s])/);
|
|
374
|
+
return rawParts
|
|
375
|
+
.map((s) => s.replaceAll('\u0001', '.').replaceAll('\u0002', '!').replaceAll('\u0003', '?').trim())
|
|
376
|
+
.filter((s) => s.length > 0);
|
|
377
|
+
}
|
|
378
|
+
export function runUncitedSentenceCheck(patch) {
|
|
379
|
+
const narratives = Array.isArray(patch.narratives) ? patch.narratives : [];
|
|
380
|
+
let totalSentences = 0;
|
|
381
|
+
let citedSentences = 0;
|
|
382
|
+
const uncitedSentences = [];
|
|
383
|
+
for (const rawNar of narratives) {
|
|
384
|
+
if (!isPlainRecord(rawNar)) {
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const body = typeof rawNar.body_md === 'string' ? rawNar.body_md : '';
|
|
388
|
+
if (!body) {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const narId = typeof rawNar.id === 'string' ? rawNar.id : 'unknown';
|
|
392
|
+
const withoutCode = body.replaceAll(/```[\s\S]*?```/g, '\n');
|
|
393
|
+
const lines = withoutCode.replaceAll('\r\n', '\n').split('\n');
|
|
394
|
+
const proseParagraphs = [];
|
|
395
|
+
let current = [];
|
|
396
|
+
const flush = () => {
|
|
397
|
+
if (current.length > 0) {
|
|
398
|
+
proseParagraphs.push(current.join(' ').trim());
|
|
399
|
+
current = [];
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
for (const rawLine of lines) {
|
|
403
|
+
const line = rawLine.trim();
|
|
404
|
+
if (!line) {
|
|
405
|
+
flush();
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (/^#{1,6}\s/.test(line) ||
|
|
409
|
+
line.startsWith('>') ||
|
|
410
|
+
/^[-*_]{3,}$/.test(line) ||
|
|
411
|
+
line.startsWith('|') ||
|
|
412
|
+
/^\[\^[^\]]+\]:/.test(line) ||
|
|
413
|
+
line.startsWith('![')) {
|
|
414
|
+
flush();
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (/^(?:[-*+]|\d+[.)])\s/.test(line)) {
|
|
418
|
+
flush();
|
|
419
|
+
const stripped = line.replace(/^(?:[-*+]|\d+[.)])\s+/, '').trim();
|
|
420
|
+
if (stripped.endsWith(':') ||
|
|
421
|
+
!/[.!?](?:\[\^[^\]]+\])*$/.test(stripped) ||
|
|
422
|
+
stripped.length < 40) {
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
proseParagraphs.push(stripped);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
if (/^\*\*[^*]+\*\*:?$/.test(line)) {
|
|
429
|
+
flush();
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
current.push(line);
|
|
433
|
+
}
|
|
434
|
+
flush();
|
|
435
|
+
for (let pIdx = 0; pIdx < proseParagraphs.length; pIdx += 1) {
|
|
436
|
+
const sentences = splitParagraphIntoSentences(proseParagraphs[pIdx]);
|
|
437
|
+
for (const sentence of sentences) {
|
|
438
|
+
if (sentence.split(/\s+/).length < 4) {
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
totalSentences += 1;
|
|
442
|
+
if (INLINE_CITATION_RE.test(sentence)) {
|
|
443
|
+
citedSentences += 1;
|
|
444
|
+
}
|
|
445
|
+
else {
|
|
446
|
+
uncitedSentences.push({
|
|
447
|
+
narrative_id: narId,
|
|
448
|
+
paragraph: pIdx + 1,
|
|
449
|
+
text: sentence.length > 220 ? `${sentence.slice(0, 217)}...` : sentence,
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return {
|
|
456
|
+
ok: uncitedSentences.length === 0,
|
|
457
|
+
totalSentences,
|
|
458
|
+
citedSentences,
|
|
459
|
+
uncitedCount: uncitedSentences.length,
|
|
460
|
+
uncitedSentences,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
export function inspectImageBuffer(buf) {
|
|
464
|
+
if (buf.length < 12) {
|
|
465
|
+
return { valid: false, format: 'unknown', width: null, height: null, error: 'file too short' };
|
|
466
|
+
}
|
|
467
|
+
// PNG: 89 50 4E 47 0D 0A 1A 0A, IHDR width/height at offsets 16..24.
|
|
468
|
+
if (buf[0] === 0x89 &&
|
|
469
|
+
buf[1] === 0x50 &&
|
|
470
|
+
buf[2] === 0x4e &&
|
|
471
|
+
buf[3] === 0x47 &&
|
|
472
|
+
buf[4] === 0x0d &&
|
|
473
|
+
buf[5] === 0x0a &&
|
|
474
|
+
buf[6] === 0x1a &&
|
|
475
|
+
buf[7] === 0x0a) {
|
|
476
|
+
if (buf.length < 24) {
|
|
477
|
+
return { valid: false, format: 'png', width: null, height: null, error: 'truncated PNG IHDR' };
|
|
478
|
+
}
|
|
479
|
+
return {
|
|
480
|
+
valid: true,
|
|
481
|
+
format: 'png',
|
|
482
|
+
width: buf.readUInt32BE(16),
|
|
483
|
+
height: buf.readUInt32BE(20),
|
|
484
|
+
error: null,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
// JPEG: FF D8 FF
|
|
488
|
+
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
|
|
489
|
+
let offset = 2;
|
|
490
|
+
while (offset + 4 < buf.length) {
|
|
491
|
+
while (offset < buf.length && buf[offset] !== 0xff) {
|
|
492
|
+
offset += 1;
|
|
493
|
+
}
|
|
494
|
+
while (offset < buf.length && buf[offset] === 0xff) {
|
|
495
|
+
offset += 1;
|
|
496
|
+
}
|
|
497
|
+
if (offset >= buf.length) {
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
const marker = buf[offset];
|
|
501
|
+
offset += 1;
|
|
502
|
+
if (marker === 0xd9 || marker === 0xda) {
|
|
503
|
+
break;
|
|
504
|
+
}
|
|
505
|
+
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (offset + 2 > buf.length) {
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
const segLen = buf.readUInt16BE(offset);
|
|
512
|
+
if (segLen < 2 || offset + segLen > buf.length) {
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
const isSof = (marker >= 0xc0 && marker <= 0xc3) ||
|
|
516
|
+
(marker >= 0xc5 && marker <= 0xc7) ||
|
|
517
|
+
(marker >= 0xc9 && marker <= 0xcb) ||
|
|
518
|
+
(marker >= 0xcd && marker <= 0xcf);
|
|
519
|
+
if (isSof && segLen >= 7) {
|
|
520
|
+
const height = buf.readUInt16BE(offset + 3);
|
|
521
|
+
const width = buf.readUInt16BE(offset + 5);
|
|
522
|
+
return { valid: true, format: 'jpeg', width, height, error: null };
|
|
523
|
+
}
|
|
524
|
+
offset += segLen;
|
|
525
|
+
}
|
|
526
|
+
return { valid: true, format: 'jpeg', width: null, height: null, error: null };
|
|
527
|
+
}
|
|
528
|
+
// WebP: RIFF....WEBP
|
|
529
|
+
if (buf.subarray(0, 4).toString('ascii') === 'RIFF' &&
|
|
530
|
+
buf.subarray(8, 12).toString('ascii') === 'WEBP') {
|
|
531
|
+
const chunk = buf.subarray(12, 16).toString('ascii');
|
|
532
|
+
if (chunk === 'VP8X' && buf.length >= 30) {
|
|
533
|
+
const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16));
|
|
534
|
+
const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16));
|
|
535
|
+
return { valid: true, format: 'webp', width, height, error: null };
|
|
536
|
+
}
|
|
537
|
+
if (chunk === 'VP8 ' && buf.length >= 30) {
|
|
538
|
+
const width = buf.readUInt16LE(26) & 0x3fff;
|
|
539
|
+
const height = buf.readUInt16LE(28) & 0x3fff;
|
|
540
|
+
return { valid: true, format: 'webp', width, height, error: null };
|
|
541
|
+
}
|
|
542
|
+
if (chunk === 'VP8L' && buf.length >= 25) {
|
|
543
|
+
const bits = buf.readUInt32LE(21);
|
|
544
|
+
const width = (bits & 0x3fff) + 1;
|
|
545
|
+
const height = ((bits >> 14) & 0x3fff) + 1;
|
|
546
|
+
return { valid: true, format: 'webp', width, height, error: null };
|
|
547
|
+
}
|
|
548
|
+
return { valid: true, format: 'webp', width: null, height: null, error: null };
|
|
549
|
+
}
|
|
550
|
+
// GIF87a / GIF89a
|
|
551
|
+
const sig6 = buf.subarray(0, 6).toString('ascii');
|
|
552
|
+
if ((sig6 === 'GIF87a' || sig6 === 'GIF89a') && buf.length >= 10) {
|
|
553
|
+
return {
|
|
554
|
+
valid: true,
|
|
555
|
+
format: 'gif',
|
|
556
|
+
width: buf.readUInt16LE(6),
|
|
557
|
+
height: buf.readUInt16LE(8),
|
|
558
|
+
error: null,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
return {
|
|
562
|
+
valid: false,
|
|
563
|
+
format: 'unknown',
|
|
564
|
+
width: null,
|
|
565
|
+
height: null,
|
|
566
|
+
error: 'unrecognized image magic header',
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
export function runScanInventoryCheck(repoDir, packageDir, patch) {
|
|
570
|
+
const scansDir = path.join(packageDir, 'scans');
|
|
571
|
+
const archiveMediaRoot = path.join(repoDir, 'archive-media');
|
|
572
|
+
const hasArchiveMedia = fs.existsSync(archiveMediaRoot) && fs.statSync(archiveMediaRoot).isDirectory();
|
|
573
|
+
const mediaRoot = hasArchiveMedia ? archiveMediaRoot : repoDir;
|
|
574
|
+
const errors = [];
|
|
575
|
+
const warnings = [];
|
|
576
|
+
const files = [];
|
|
577
|
+
const checkedPaths = new Set();
|
|
578
|
+
const inspectFile = (diskPath, mediaId, fileUrl, source) => {
|
|
579
|
+
const resolved = path.resolve(diskPath);
|
|
580
|
+
if (checkedPaths.has(resolved)) {
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
checkedPaths.add(resolved);
|
|
584
|
+
if (!fs.existsSync(resolved)) {
|
|
585
|
+
errors.push(`Missing scan file for ${mediaId ?? 'scans/'}: ${fileUrl ?? resolved}`);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
const stat = fs.statSync(resolved);
|
|
589
|
+
if (stat.size === 0) {
|
|
590
|
+
errors.push(`Empty (0 byte) scan file: ${resolved}`);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const fd = fs.openSync(resolved, 'r');
|
|
594
|
+
const readLen = Math.min(stat.size, 65_536);
|
|
595
|
+
const buf = Buffer.allocUnsafe(readLen);
|
|
596
|
+
try {
|
|
597
|
+
fs.readSync(fd, buf, 0, readLen, 0);
|
|
598
|
+
}
|
|
599
|
+
finally {
|
|
600
|
+
fs.closeSync(fd);
|
|
601
|
+
}
|
|
602
|
+
const info = inspectImageBuffer(buf);
|
|
603
|
+
if (!info.valid) {
|
|
604
|
+
errors.push(`Invalid image file (${info.error}): ${resolved}`);
|
|
605
|
+
}
|
|
606
|
+
if (stat.size < MIN_SCAN_WARN_BYTES) {
|
|
607
|
+
warnings.push(`Tiny scan (< 10 KB, ${stat.size} bytes): ${path.basename(resolved)}`);
|
|
608
|
+
}
|
|
609
|
+
else if (stat.size > MAX_SCAN_WARN_BYTES) {
|
|
610
|
+
warnings.push(`Huge scan (> 10 MB, ${(stat.size / (1024 * 1024)).toFixed(1)} MB): ${path.basename(resolved)}`);
|
|
611
|
+
}
|
|
612
|
+
files.push({
|
|
613
|
+
media_id: mediaId,
|
|
614
|
+
file: fileUrl ?? path.basename(resolved),
|
|
615
|
+
disk_path: resolved,
|
|
616
|
+
source,
|
|
617
|
+
format: info.format,
|
|
618
|
+
width: info.width,
|
|
619
|
+
height: info.height,
|
|
620
|
+
bytes: stat.size,
|
|
621
|
+
kb: Number((stat.size / 1024).toFixed(1)),
|
|
622
|
+
valid: info.valid,
|
|
623
|
+
});
|
|
624
|
+
};
|
|
625
|
+
const referencedBasenames = new Set();
|
|
626
|
+
for (const rawItem of Array.isArray(patch.media) ? patch.media : []) {
|
|
627
|
+
const item = isPlainRecord(rawItem) ? rawItem : {};
|
|
628
|
+
const mediaId = typeof item.id === 'string' ? item.id : null;
|
|
629
|
+
const fileUrl = typeof item.file === 'string' ? item.file : null;
|
|
630
|
+
if (!fileUrl) {
|
|
631
|
+
errors.push(`Media entry '${mediaId ?? 'unknown'}' missing 'file' field.`);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
const base = path.basename(fileUrl);
|
|
635
|
+
referencedBasenames.add(base);
|
|
636
|
+
const stagedCandidate = path.join(scansDir, base);
|
|
637
|
+
const repoCandidate = path.resolve(mediaRoot, ...fileUrl.replace(/^\/+/, '').split('/'));
|
|
638
|
+
if (fs.existsSync(stagedCandidate)) {
|
|
639
|
+
inspectFile(stagedCandidate, mediaId, fileUrl, 'package_scans');
|
|
640
|
+
}
|
|
641
|
+
else if (fs.existsSync(repoCandidate)) {
|
|
642
|
+
inspectFile(repoCandidate, mediaId, fileUrl, 'repo_media');
|
|
643
|
+
}
|
|
644
|
+
else {
|
|
645
|
+
errors.push(`Missing scan for media '${mediaId ?? 'unknown'}': '${fileUrl}' not found in scans/ or repo media.`);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
const unreferencedScans = [];
|
|
649
|
+
if (fs.existsSync(scansDir) && fs.statSync(scansDir).isDirectory()) {
|
|
650
|
+
const entries = fs
|
|
651
|
+
.readdirSync(scansDir, { withFileTypes: true })
|
|
652
|
+
.toSorted((a, b) => a.name.localeCompare(b.name));
|
|
653
|
+
for (const entry of entries) {
|
|
654
|
+
if (entry.isDirectory()) {
|
|
655
|
+
errors.push(`Forbidden subdirectory inside scans/: ${entry.name}`);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (!entry.isFile()) {
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
const fullPath = path.join(scansDir, entry.name);
|
|
662
|
+
if (!referencedBasenames.has(entry.name)) {
|
|
663
|
+
unreferencedScans.push(entry.name);
|
|
664
|
+
warnings.push(`Unreferenced file in scans/: ${entry.name}`);
|
|
665
|
+
inspectFile(fullPath, null, entry.name, 'unreferenced_scan');
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return {
|
|
670
|
+
ok: errors.length === 0,
|
|
671
|
+
checkedCount: files.length,
|
|
672
|
+
unreferencedScans,
|
|
673
|
+
files,
|
|
674
|
+
errors,
|
|
675
|
+
warnings,
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function countZeroCoordPlaces(patch) {
|
|
679
|
+
const bad = [];
|
|
680
|
+
for (const rawPl of Array.isArray(patch.places) ? patch.places : []) {
|
|
681
|
+
const pl = isPlainRecord(rawPl) ? rawPl : {};
|
|
682
|
+
const lat = Number(pl.lat);
|
|
683
|
+
const lng = Number(pl.lng ?? pl.lon);
|
|
684
|
+
if (!Number.isFinite(lat) ||
|
|
685
|
+
!Number.isFinite(lng) ||
|
|
686
|
+
(Math.abs(lat) < 1e-9 && Math.abs(lng) < 1e-9)) {
|
|
687
|
+
bad.push(typeof pl.id === 'string' ? pl.id : 'unknown');
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return bad;
|
|
691
|
+
}
|
|
692
|
+
export function formatAuditTextReport(report) {
|
|
693
|
+
const lines = [];
|
|
694
|
+
const status = report.ok ? 'PASS' : 'FAIL';
|
|
695
|
+
lines.push(`Audit [${status}] ${report.person_id} (${report.duration_ms} ms)`);
|
|
696
|
+
lines.push(` Repo: ${report.repo}`);
|
|
697
|
+
lines.push(` 1. Chronology: ${report.checks.chronology.ok ? 'PASS' : 'FAIL'} | ` +
|
|
698
|
+
`${report.checks.chronology.birth_edtf ?? '?'} .. ${report.checks.chronology.death_edtf ?? '?'} ` +
|
|
699
|
+
`(${report.checks.chronology.lifespan.label ?? 'unknown'}) | ` +
|
|
700
|
+
`events=${report.checks.chronology.checkedEvents} errors=${report.checks.chronology.errors.length} warnings=${report.checks.chronology.warnings.length}`);
|
|
701
|
+
lines.push(` 2. Privacy/Style: ${report.checks.privacy.ok ? 'PASS' : 'FAIL'} | ` +
|
|
702
|
+
`livingHits=${report.checks.privacy.livingNameHits.length} ssn=${report.checks.privacy.ssnHits.length} ` +
|
|
703
|
+
`phones=${report.checks.privacy.phoneHits.length} emDashes=${report.checks.privacy.emDashCount}`);
|
|
704
|
+
lines.push(` 3. Citations: ${report.checks.citations.ok ? 'PASS' : 'WARN'} | ` +
|
|
705
|
+
`cited=${report.checks.citations.citedSentences}/${report.checks.citations.totalSentences} ` +
|
|
706
|
+
`uncited=${report.checks.citations.uncitedCount} inlineTokens=${report.checks.dryRun.inlineCitationCount}`);
|
|
707
|
+
lines.push(` 4. Scans: ${report.checks.scans.ok ? 'PASS' : 'FAIL'} | ` +
|
|
708
|
+
`checked=${report.checks.scans.checkedCount} errors=${report.checks.scans.errors.length} warnings=${report.checks.scans.warnings.length}`);
|
|
709
|
+
lines.push(` 5. Dry-Run: ${report.checks.dryRun.ok ? 'PASS' : 'FAIL'} (${report.checks.dryRun.durationMs} ms) | ` +
|
|
710
|
+
`reviewFlags=${report.checks.dryRun.reviewFlags} livingLeaks=${report.checks.dryRun.livingLeaks} zeroCoordPlaces=${report.zeroCoordinatePlaces.length}`);
|
|
711
|
+
for (const err of report.errors) {
|
|
712
|
+
lines.push(` ERROR: ${err}`);
|
|
713
|
+
}
|
|
714
|
+
for (const warn of report.warnings) {
|
|
715
|
+
lines.push(` WARN: ${warn}`);
|
|
716
|
+
}
|
|
717
|
+
return `${lines.join('\n')}\n`;
|
|
718
|
+
}
|
|
719
|
+
async function runInProcessIntegrateDryRun(params) {
|
|
720
|
+
const t0 = performance.now();
|
|
721
|
+
try {
|
|
722
|
+
const res = await runIntegrateCommand({
|
|
723
|
+
repoDir: params.repoDir,
|
|
724
|
+
personId: params.personId,
|
|
725
|
+
packageDir: params.packageDir,
|
|
726
|
+
dryRun: true,
|
|
727
|
+
});
|
|
728
|
+
return {
|
|
729
|
+
ok: res.ok,
|
|
730
|
+
durationMs: Math.round(performance.now() - t0),
|
|
731
|
+
inlineCitationCount: res.inlineCitationCount,
|
|
732
|
+
reviewFlags: res.validation.privateReviewFlags + res.validation.publicReviewFlags,
|
|
733
|
+
livingLeaks: res.validation.livingLeaks,
|
|
734
|
+
counts: res.counts,
|
|
735
|
+
error: null,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
catch (err) {
|
|
739
|
+
return {
|
|
740
|
+
ok: false,
|
|
741
|
+
durationMs: Math.round(performance.now() - t0),
|
|
742
|
+
inlineCitationCount: 0,
|
|
743
|
+
reviewFlags: 0,
|
|
744
|
+
livingLeaks: null,
|
|
745
|
+
counts: null,
|
|
746
|
+
error: err instanceof Error ? err.message : String(err),
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
export async function runAuditCommand(options) {
|
|
751
|
+
const t0 = performance.now();
|
|
752
|
+
const repoDir = path.resolve(options.repoDir?.trim() || process.cwd());
|
|
753
|
+
const personId = options.personId.trim();
|
|
754
|
+
if (!personId) {
|
|
755
|
+
throw new CliValidationError('Missing required option `--person <person_id>`.');
|
|
756
|
+
}
|
|
757
|
+
if (!SAFE_PERSON_ID_RE.test(personId)) {
|
|
758
|
+
throw new CliValidationError(`Invalid person_id '${personId}'.`);
|
|
759
|
+
}
|
|
760
|
+
const packageDir = path.resolve(options.packageDir?.trim() || path.join(repoDir, 'research', 'people', personId));
|
|
761
|
+
const patchPath = path.join(packageDir, 'patch.json');
|
|
762
|
+
const dossierPath = path.join(packageDir, 'dossier.md');
|
|
763
|
+
if (!fs.existsSync(patchPath)) {
|
|
764
|
+
throw new CliValidationError(`Missing patch.json at ${patchPath}.`);
|
|
765
|
+
}
|
|
766
|
+
const dataDir = path.join(repoDir, 'data');
|
|
767
|
+
const peoplePath = path.join(dataDir, 'people.yaml');
|
|
768
|
+
if (!fs.existsSync(peoplePath)) {
|
|
769
|
+
throw new CliValidationError(`Missing data/people.yaml at ${peoplePath}.`);
|
|
770
|
+
}
|
|
771
|
+
const [patchText, dossierText, peopleText, eventsText, configText] = await Promise.all([
|
|
772
|
+
readFile(patchPath, 'utf8'),
|
|
773
|
+
fs.existsSync(dossierPath) ? readFile(dossierPath, 'utf8') : Promise.resolve(''),
|
|
774
|
+
readFile(peoplePath, 'utf8'),
|
|
775
|
+
fs.existsSync(path.join(dataDir, 'events.yaml'))
|
|
776
|
+
? readFile(path.join(dataDir, 'events.yaml'), 'utf8')
|
|
777
|
+
: Promise.resolve(''),
|
|
778
|
+
fs.existsSync(path.join(repoDir, 'kinloom.config.yaml'))
|
|
779
|
+
? readFile(path.join(repoDir, 'kinloom.config.yaml'), 'utf8')
|
|
780
|
+
: Promise.resolve(''),
|
|
781
|
+
]);
|
|
782
|
+
const parsedPatch = JSON.parse(patchText);
|
|
783
|
+
if (!isPlainRecord(parsedPatch)) {
|
|
784
|
+
throw new CliValidationError(`patch.json at ${patchPath} must contain a JSON object.`);
|
|
785
|
+
}
|
|
786
|
+
const patch = parsedPatch;
|
|
787
|
+
const privacyConfig = configText
|
|
788
|
+
? parseKinloomConfigYaml(configText).privacy
|
|
789
|
+
: {};
|
|
790
|
+
const peopleBlocks = splitTopLevelYamlList(peopleText);
|
|
791
|
+
const relevantPeopleBlocks = peopleBlocks.filter((block) => {
|
|
792
|
+
const id = extractYamlBlockId(block);
|
|
793
|
+
if (id === personId) {
|
|
794
|
+
return true;
|
|
795
|
+
}
|
|
796
|
+
if (/\b(?:is_living|living):\s*true\b/.test(block)) {
|
|
797
|
+
return true;
|
|
798
|
+
}
|
|
799
|
+
const dm = /^\s+death_edtf:\s*(.*)$/m.exec(block);
|
|
800
|
+
const dv = dm ? dm[1].trim().replaceAll(/^["']|["']$/g, '') : '';
|
|
801
|
+
return dv.length === 0 || dv === 'null' || dv === '~';
|
|
802
|
+
});
|
|
803
|
+
const parsedPeople = parseMatchingYamlBlocks(relevantPeopleBlocks);
|
|
804
|
+
const targetPerson = parsedPeople.find((p) => p.id === personId) ?? null;
|
|
805
|
+
const livingPeople = parsedPeople.filter((p) => {
|
|
806
|
+
if (p.id === personId) {
|
|
807
|
+
return false;
|
|
808
|
+
}
|
|
809
|
+
if (p.is_living === true || p.living === true) {
|
|
810
|
+
return true;
|
|
811
|
+
}
|
|
812
|
+
const birthEdtf = asString(p.birth_edtf).trim();
|
|
813
|
+
const deathEdtf = asString(p.death_edtf).trim();
|
|
814
|
+
return resolveEffectiveLiving({ is_living: false, birth_edtf: birthEdtf, death_edtf: deathEdtf }, privacyConfig);
|
|
815
|
+
});
|
|
816
|
+
const existingPersonEventBlocks = splitTopLevelYamlList(eventsText).filter((b) => b.includes(personId));
|
|
817
|
+
const existingPersonEvents = parseMatchingYamlBlocks(existingPersonEventBlocks).filter((ev) => Array.isArray(ev.participants) &&
|
|
818
|
+
ev.participants.some((pt) => isPlainRecord(pt) && pt.person_id === personId));
|
|
819
|
+
const chronology = runChronologyCheck(targetPerson, patch, existingPersonEvents);
|
|
820
|
+
const privacy = runPrivacyAndStyleScan(dossierText, patch, livingPeople);
|
|
821
|
+
const citations = runUncitedSentenceCheck(patch);
|
|
822
|
+
const scans = runScanInventoryCheck(repoDir, packageDir, patch);
|
|
823
|
+
const zeroCoordinatePlaces = countZeroCoordPlaces(patch);
|
|
824
|
+
const dryRun = await runInProcessIntegrateDryRun({ repoDir, personId, packageDir });
|
|
825
|
+
const allErrors = [
|
|
826
|
+
...chronology.errors.map((e) => `chronology: ${e}`),
|
|
827
|
+
...privacy.errors.map((e) => `privacy: ${e}`),
|
|
828
|
+
...scans.errors.map((e) => `scans: ${e}`),
|
|
829
|
+
...zeroCoordinatePlaces.map((id) => `places: zero or missing coordinates on '${id}'`),
|
|
830
|
+
...(dryRun.error ? [`dryRun: ${dryRun.error}`] : []),
|
|
831
|
+
];
|
|
832
|
+
const allWarnings = [
|
|
833
|
+
...chronology.warnings.map((w) => `chronology: ${w}`),
|
|
834
|
+
...privacy.warnings.map((w) => `style: ${w}`),
|
|
835
|
+
...(citations.uncitedCount > 0
|
|
836
|
+
? [`citations: ${citations.uncitedCount} uncited prose sentence(s) in body_md`]
|
|
837
|
+
: []),
|
|
838
|
+
...scans.warnings.map((w) => `scans: ${w}`),
|
|
839
|
+
];
|
|
840
|
+
const durationMs = Math.round(performance.now() - t0);
|
|
841
|
+
const baseReport = {
|
|
842
|
+
ok: allErrors.length === 0,
|
|
843
|
+
strictOk: allErrors.length === 0 && citations.uncitedCount === 0 && privacy.emDashCount === 0,
|
|
844
|
+
repo: repoDir,
|
|
845
|
+
person_id: personId,
|
|
846
|
+
package_dir: packageDir,
|
|
847
|
+
duration_ms: durationMs,
|
|
848
|
+
zeroCoordinatePlaces,
|
|
849
|
+
checks: {
|
|
850
|
+
chronology,
|
|
851
|
+
privacy,
|
|
852
|
+
citations,
|
|
853
|
+
scans,
|
|
854
|
+
dryRun,
|
|
855
|
+
},
|
|
856
|
+
errors: allErrors,
|
|
857
|
+
warnings: allWarnings,
|
|
858
|
+
};
|
|
859
|
+
const rendered = options.json
|
|
860
|
+
? `${JSON.stringify(baseReport, null, 2)}\n`
|
|
861
|
+
: formatAuditTextReport(baseReport);
|
|
862
|
+
return {
|
|
863
|
+
...baseReport,
|
|
864
|
+
rendered,
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
//# sourceMappingURL=audit.js.map
|