strom-research 1.36.0 → 1.37.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.cs.md +42 -0
  2. package/CHANGELOG.de.md +50 -0
  3. package/CHANGELOG.md +45 -0
  4. package/CHANGELOG.pl.md +46 -0
  5. package/assets/lang/cs.json +40 -4
  6. package/assets/lang/de.json +40 -4
  7. package/assets/lang/pl.json +40 -4
  8. package/assets/strom-doc/cs/R12-where-the-agent-works.md +2 -2
  9. package/assets/strom-doc/de/R12-where-the-agent-works.md +2 -2
  10. package/assets/strom-doc/en/R12-where-the-agent-works.md +2 -2
  11. package/assets/strom-doc/pl/R12-where-the-agent-works.md +1 -1
  12. package/dist/brief/brief.js +43 -5
  13. package/dist/cli/menu-links.js +3 -2
  14. package/dist/cli/menu-waiting.js +3 -1
  15. package/dist/cli/ui.js +36 -4
  16. package/dist/commands/archives.js +11 -3
  17. package/dist/commands/browse.js +5 -1
  18. package/dist/commands/fixchecks.js +21 -1
  19. package/dist/commands/fixes.js +38 -6
  20. package/dist/commands/intake.js +10 -2
  21. package/dist/commands/links.js +5 -4
  22. package/dist/commands/media.js +14 -4
  23. package/dist/commands/people.js +2 -0
  24. package/dist/commands/session.js +54 -1
  25. package/dist/commands/setup.js +1 -1
  26. package/dist/commands/sync.js +113 -54
  27. package/dist/commands/tasks.js +2 -2
  28. package/dist/core/actions.js +4 -0
  29. package/dist/core/appmedia.js +207 -7
  30. package/dist/core/changelog.js +7 -0
  31. package/dist/core/contact.js +220 -0
  32. package/dist/core/contactfix.js +260 -0
  33. package/dist/core/floor.js +13 -3
  34. package/dist/core/import.js +53 -5
  35. package/dist/core/inboxwait.js +93 -18
  36. package/dist/core/links.js +8 -2
  37. package/dist/core/lists.js +117 -0
  38. package/dist/core/live.js +273 -39
  39. package/dist/core/machine.js +28 -0
  40. package/dist/core/material.js +14 -1
  41. package/dist/core/mediaqueue.js +1 -1
  42. package/dist/core/metrics.js +32 -1
  43. package/dist/core/originals.js +28 -9
  44. package/dist/core/overview.js +1 -0
  45. package/dist/core/ownsave.js +43 -0
  46. package/dist/core/phrases.js +4 -0
  47. package/dist/core/queue.js +1 -1
  48. package/dist/core/receive.js +9 -3
  49. package/dist/core/runstate.js +2 -1
  50. package/dist/core/session.js +16 -0
  51. package/dist/core/shaindex.js +31 -5
  52. package/dist/core/shortcut.js +2 -1
  53. package/dist/core/stromapp.js +2 -3
  54. package/dist/core/sync.js +242 -27
  55. package/dist/core/terms.js +44 -8
  56. package/dist/core/text.js +11 -0
  57. package/dist/core/tree.js +1 -1
  58. package/dist/core/validate.js +21 -0
  59. package/dist/core/waiting.js +2 -1
  60. package/dist/core/web.js +49 -7
  61. package/dist/core/webfull.js +105 -0
  62. package/dist/gedcom/export.js +8 -0
  63. package/dist/gedcom/validate.js +2 -1
  64. package/package.json +4 -1
@@ -18,8 +18,9 @@ import { safeFolderName } from "../core/text.js";
18
18
  import { humanAge } from "../core/age.js";
19
19
  import { now, Tree } from "../core/tree.js";
20
20
  import { actsAsArchive } from "../core/state.js";
21
- import { applySync, asksPerson, mediaWritten, guardedChange, houseWords, discardReceived, nothingSince, notWrittenList, withoutImages, planSync, readTreeFile, treeFileKept, receivedAll, receivedPending, receivedSince, receivedOf, removedByItsDecision, settleReceived, SYNC_INBOX, syncConflicts, undoReceived, undoSync } from "../core/sync.js";
21
+ import { applySync, asksPerson, mediaWritten, guardedChange, houseWords, discardReceived, nothingSince, notWrittenList, withoutImages, planSync, readTreeFile, treeFileKept, receivedAll, receivedPending, receivedSince, receivedOf, removedByItsDecision, settleReceived, countedReceived, planState, SYNC_INBOX, syncConflicts, undoReceived, undoSync } from "../core/sync.js";
22
22
  import { labels } from "../gedcom/labels.js";
23
+ import { mediaResolver } from "../core/appmedia.js";
23
24
  import { startLive } from "../core/live.js";
24
25
  import { appSendsChanges, sendAppUrl, stromAppUrl } from "../core/stromapp.js";
25
26
  import { appWindow, openAppIn, replaceGone } from "../core/appbrowser.js";
@@ -202,44 +203,47 @@ function changeLine(tree, c, incoming, lang, readings, decidePerson = false) {
202
203
  ? !tree.personWrites ? "ui.sync.do.main.kept" : `ui.sync.do.main${c.mainOff ? ".off" : ""}`
203
204
  : c.kind === "fact.uncite" && c.action === "user"
204
205
  ? !tree.personWrites ? "ui.sync.do.uncite.kept" : "ui.sync.do.uncite"
205
- : c.kind === "ids.add"
206
- ? "ui.sync.do.ids"
207
- : c.kind === "child.parents"
208
- ? "ui.sync.do.parents"
209
- : c.kind === "person.removed"
210
- ? `ui.sync.do.removed${c.action === "conflict" ? ".conflict" : ""}`
211
- : c.kind === "name.changed" && c.action === "user"
212
- ? "ui.sync.do.name.user"
213
- : c.kind === "name.shown"
214
- ? `ui.sync.do.name.shown${c.action === "conflict" ? ".conflict" : ""}`
215
- : c.kind === "name.now"
216
- ? "ui.sync.do.name.now"
217
- : c.kind === "name.gone"
218
- ? `ui.sync.do.name.${c.action === "remove" ? "gone" : "kept"}`
219
- : c.kind === "name.title" && (c.action === "add" || c.action === "user")
220
- ? `ui.sync.do.title${c.action === "user" ? ".user" : ""}`
221
- : c.kind === "note.changed" && c.action !== "pick"
222
- ? "ui.sync.do.note.changed"
223
- : c.kind === "family.union" && c.action !== "report"
224
- ? "ui.sync.do.family.union"
225
- : c.kind === "fact.detail" && c.action === "add"
226
- ? "ui.sync.do.detail"
227
- : (c.kind === "fact.note" || c.kind === "fact.part.note") && (c.action === "add" || c.action === "correct")
228
- ? `ui.sync.do.${c.kind}${c.action === "add" ? ".add" : ""}`
229
- : c.kind === "fact.part" && (c.action === "add" || c.action === "user")
230
- ? `ui.sync.do.part${c.action === "user" ? ".user" : ""}`
231
- : c.kind === "source.title"
232
- ? `ui.sync.do.source.title${c.action === "add" ? ".beside" : c.action === "user" ? ".user" : ""}`
233
- : c.kind === "source.new" && c.reading?.ok
234
- ? `ui.sync.do.source.new.reading${c.reading.edited ? ".edited" : ""}`
235
- : c.kind.startsWith("source.") || c.kind === "fact.cite" || c.kind === "person.cite" || c.kind === "family.cite"
236
- ? `ui.sync.do.${c.kind}${c.reads || (c.kind === "source.new" && newReads(c, incoming)) ? ".read" : ""}`
237
- : c.kind === "fact.new" && c.reads
238
- ? "ui.sync.do.reading"
239
- // a fact on an entry of the research's reading of a document: as sure as its readers read it
240
- : c.kind === "fact.new" && c.fact?.cites?.some((x) => readings?.get(x.source)?.ok)
241
- ? "ui.sync.do.reading.document"
242
- : `ui.sync.do.${c.action}`;
206
+ // the person's contact (spec 134 U11)
207
+ : c.kind === "contact.email"
208
+ ? `ui.sync.do.contact.${c.action !== "remove" ? "add" : tree.personWrites ? "remove" : "kept"}`
209
+ : c.kind === "ids.add"
210
+ ? "ui.sync.do.ids"
211
+ : c.kind === "child.parents"
212
+ ? "ui.sync.do.parents"
213
+ : c.kind === "person.removed"
214
+ ? `ui.sync.do.removed${c.action === "conflict" ? ".conflict" : ""}`
215
+ : c.kind === "name.changed" && c.action === "user"
216
+ ? "ui.sync.do.name.user"
217
+ : c.kind === "name.shown"
218
+ ? `ui.sync.do.name.shown${c.action === "conflict" ? ".conflict" : ""}`
219
+ : c.kind === "name.now"
220
+ ? "ui.sync.do.name.now"
221
+ : c.kind === "name.gone"
222
+ ? `ui.sync.do.name.${c.action === "remove" ? "gone" : "kept"}`
223
+ : c.kind === "name.title" && (c.action === "add" || c.action === "user")
224
+ ? `ui.sync.do.title${c.action === "user" ? ".user" : ""}`
225
+ : c.kind === "note.changed" && c.action !== "pick"
226
+ ? "ui.sync.do.note.changed"
227
+ : c.kind === "family.union" && c.action !== "report"
228
+ ? "ui.sync.do.family.union"
229
+ : c.kind === "fact.detail" && c.action === "add"
230
+ ? "ui.sync.do.detail"
231
+ : (c.kind === "fact.note" || c.kind === "fact.part.note") && (c.action === "add" || c.action === "correct")
232
+ ? `ui.sync.do.${c.kind}${c.action === "add" ? ".add" : ""}`
233
+ : c.kind === "fact.part" && (c.action === "add" || c.action === "user")
234
+ ? `ui.sync.do.part${c.action === "user" ? ".user" : ""}`
235
+ : c.kind === "source.title"
236
+ ? `ui.sync.do.source.title${c.action === "add" ? ".beside" : c.action === "user" ? ".user" : ""}`
237
+ : c.kind === "source.new" && c.reading?.ok
238
+ ? `ui.sync.do.source.new.reading${c.reading.edited ? ".edited" : ""}`
239
+ : c.kind.startsWith("source.") || c.kind === "fact.cite" || c.kind === "person.cite" || c.kind === "family.cite"
240
+ ? `ui.sync.do.${c.kind}${c.reads || (c.kind === "source.new" && newReads(c, incoming)) ? ".read" : ""}`
241
+ : c.kind === "fact.new" && c.reads
242
+ ? "ui.sync.do.reading"
243
+ // a fact on an entry of the research's reading of a document: as sure as its readers read it
244
+ : c.kind === "fact.new" && c.fact?.cites?.some((x) => readings?.get(x.source)?.ok)
245
+ ? "ui.sync.do.reading.document"
246
+ : `ui.sync.do.${c.action}`;
243
247
  // an archive: nobody reads a record there, nor is an agent told — said without it
244
248
  const said = actsAsArchive(tree) && `${does}.archive` in UI ? `${does}.archive` : does;
245
249
  return `${ui(lang, key, v)} → ${ui(lang, said)}`;
@@ -337,6 +341,19 @@ function numbers(v, max) {
337
341
  }
338
342
  return out;
339
343
  }
344
+ /**
345
+ * Tests only: a pause once planned, before the count is said and the lock taken (STROM_TEST_SYNC_PLANNED=<file>) — the
346
+ * file made, waited for until it is gone (at most a minute): a test looks at the send being counted, writes meanwhile.
347
+ */
348
+ function heldAfterPlan(file) {
349
+ if (!file)
350
+ return;
351
+ fs.writeFileSync(file, "planned\n");
352
+ const until = Date.now() + 60_000;
353
+ const pause = new Int32Array(new SharedArrayBuffer(4));
354
+ while (fs.existsSync(file) && Date.now() < until)
355
+ Atomics.wait(pause, 0, 0, 50);
356
+ }
340
357
  register({
341
358
  path: ["sync"],
342
359
  summary: "A family tree coming back (the Strom app, another program): what you changed, into the research — shown first",
@@ -419,13 +436,42 @@ register({
419
436
  const syncs = tree.list("input").filter((i) => i.sync && !i.sync.undone);
420
437
  const last = syncs.reduce((a, i) => (!a || i.id > a.id ? i : a), undefined);
421
438
  const before = last?.sha === sha ? last : undefined;
439
+ // the bridge that leaves a send to this strom to count (STROM_SYNC_TELL): told as it reads it (a refusal from
440
+ // here on is the send's) and how many changes it brings, once planned — the app hears it while it is written
441
+ const tell = ctx.env.STROM_SYNC_TELL === "1" && opts.apply && !tree.dryRun ? (line) => ctx.io.stderr(`strom-sync: ${line}\n`) : undefined;
442
+ const writes = !!opts.apply && !tree.dryRun;
422
443
  if (before && !opts.again) {
423
444
  // the app sent the very same tree again: nothing waits of it
424
- if (opts.apply && !tree.dryRun)
445
+ if (writes) {
446
+ countedReceived(tree.root, file, 0);
447
+ tell?.("planned 0");
425
448
  settleReceived(tree.root, file, { state: "nothing" });
426
- return { text: ui(lang, "ui.sync.again", { input: before.id }), data: { input: before.id, changes: [] } };
449
+ }
450
+ return { text: ui(lang, "ui.sync.again", { input: before.id }), data: { input: before.id, changes: [], plans: 0 } };
427
451
  }
428
- const incoming = readTreeFile(file, tree.config.lang);
452
+ // where the time goes (ms; the bridge's line in live.log): the file read, planned (each time), the lock waited
453
+ // for, written, the send settled — planned once: again under the lock only when the research changed meanwhile
454
+ const phases = { read: 0, plan: 0, lock: 0, apply: 0, settle: 0 };
455
+ const planParts = {};
456
+ let plans = 0;
457
+ const clocked = (phase, fn) => {
458
+ const from = performance.now();
459
+ try {
460
+ return fn();
461
+ }
462
+ finally {
463
+ phases[phase] += performance.now() - from;
464
+ }
465
+ };
466
+ const timing = () => ({ phases: Object.fromEntries(Object.entries(phases).map(([k, v]) => [k, Math.round(v)])), plans, planParts: Object.fromEntries(Object.entries(planParts).map(([k, v]) => [k, Math.round(v ?? 0)])) });
467
+ // the research as the plan finds it: the same under the lock, and the plan holds (nothing written between)
468
+ const planned = writes ? planState(tree) : undefined;
469
+ tell?.("reading");
470
+ // written: the files of the app's tree it carries are kept in the shared store as they are read (spec 108 P8)
471
+ // a file it names by its hash (spec 133) found in the store or the research's own files, as the bridge's check found it
472
+ const store = ctx.settings.shared()?.value;
473
+ const reading = { store, resolve: mediaResolver(tree, store) };
474
+ const incoming = clocked("read", () => readTreeFile(file, tree.config.lang, writes ? { media: reading } : {}));
429
475
  // a Windows program's code page it was read in, characters it could not read: said, and in --json
430
476
  const said = decodingSaid(lang, path.basename(file), incoming.decoding ?? {});
431
477
  const decoding = incoming.decoding ?? {};
@@ -433,16 +479,22 @@ register({
433
479
  const sent = !!receivedOf(tree.root, file);
434
480
  // the app said it sends every file of its tree (POST /sync?media=app): a place of one it was given and no longer has goes
435
481
  const mediaApp = !!receivedOf(tree.root, file)?.mediaApp;
436
- const plan = planSync(tree, incoming, edits, { force: !!opts.force, sent, mediaApp });
482
+ const plan = clocked("plan", () => planSync(tree, incoming, edits, { force: !!opts.force, sent, mediaApp, times: planParts }));
483
+ plans++;
484
+ if (writes) {
485
+ heldAfterPlan(ctx.env.STROM_TEST_SYNC_PLANNED);
486
+ countedReceived(tree.root, file, plan.changes.length);
487
+ tell?.(`planned ${plan.changes.length}`);
488
+ }
437
489
  // a send of the app that brings nothing the research has not: nothing waits of it any more
438
- if (opts.apply && !plan.changes.length && !tree.dryRun)
439
- settleReceived(tree.root, file, { state: "nothing" });
490
+ if (writes && !plan.changes.length)
491
+ clocked("settle", () => settleReceived(tree.root, file, { state: "nothing" }));
440
492
  if (!opts.apply || !plan.changes.length || tree.dryRun) {
441
493
  if (opts.only !== undefined && !opts.apply)
442
494
  throw new UsageError("--only goes with --apply");
443
495
  return {
444
496
  text: lines(got ? ui(lang, "ui.sync.got") : undefined, ...said, planText(tree, plan, incoming, shownAs, lang, edits, ctx.settings.hypothesesDecide(tree.config) === "person")),
445
- data: { ...(got ? { received: got } : {}), ...decoding, base: plan.base, head: plan.head ?? null, partial: plan.partial, changes: plan.changes, strangers: plan.identity.strangers, ...(plan.mended ? { mended: plan.mended } : {}), ...(plan.waiting ? { waiting: plan.waiting } : {}) },
497
+ data: { ...(got ? { received: got } : {}), ...decoding, base: plan.base, head: plan.head ?? null, partial: plan.partial, changes: plan.changes, strangers: plan.identity.strangers, ...(plan.mended ? { mended: plan.mended } : {}), ...(plan.waiting ? { waiting: plan.waiting } : {}), ...timing() },
446
498
  };
447
499
  }
448
500
  const only = numbers(opts.only, plan.changes.length);
@@ -452,12 +504,18 @@ register({
452
504
  let proposed = [];
453
505
  let retracted = [];
454
506
  let written = plan;
507
+ const waited = performance.now();
455
508
  tree.withTreeLock(() => {
509
+ phases.lock += performance.now() - waited;
456
510
  // what another process wrote meanwhile counts: the changes again, now that the tree is ours — the ones picked by
457
- // number must be the ones shown; all of them are what the file brings now
458
- // the files of the app's tree it carries: their bytes kept in the shared store as they are read (spec 108 P8)
459
- const now1 = readTreeFile(file, tree.config.lang, { media: { store: ctx.settings.shared()?.value } });
460
- const fresh = planSync(tree, now1, edits, { force: !!opts.force, sent, mediaApp });
511
+ // number must be the ones shown; all of them are what the file brings now. Nothing written meanwhile (the same
512
+ // commit, nothing of data/ or strom.json apart from it): the plan made holds, with the file as it planned it
513
+ const held = planned !== undefined && planState(tree) === planned;
514
+ const now1 = held ? incoming : clocked("read", () => readTreeFile(file, tree.config.lang, { media: reading }));
515
+ const fresh = held ? plan : clocked("plan", () => planSync(tree, now1, edits, { force: !!opts.force, sent, mediaApp, times: planParts }));
516
+ if (!held)
517
+ plans++;
518
+ const applyFrom = performance.now();
461
519
  if (only && (fresh.changes.length !== plan.changes.length || fresh.changes.some((c, i) => c.kind !== plan.changes[i].kind || c.person !== plan.changes[i].person)))
462
520
  throw new UsageError("the research changed while this was shown — look again", { hint: `strom sync ${args[0] ?? file}` });
463
521
  written = fresh;
@@ -513,15 +571,16 @@ register({
513
571
  // a fact the sync brought with its original cited: queued to be verified against it (core/verify.ts)
514
572
  if (changes)
515
573
  queueVerify(tree);
574
+ phases.apply += performance.now() - applyFrom;
516
575
  });
517
576
  if (!input) {
518
- settleReceived(tree.root, file, { state: "nothing", kept: written.changes.filter((c) => c.kept).length, notWritten: notWrittenList(written.changes), skipped });
519
- return { text: lines(...said, planText(tree, written, incoming, shownAs, lang, edits), "", ui(lang, "ui.sync.nothing.taken", { file: path.basename(file) })), data: { input: null, ...decoding, applied: [], changes: written.changes } };
577
+ clocked("settle", () => settleReceived(tree.root, file, { state: "nothing", kept: written.changes.filter((c) => c.kept).length, notWritten: notWrittenList(written.changes), skipped }));
578
+ return { text: lines(...said, planText(tree, written, incoming, shownAs, lang, edits), "", ui(lang, "ui.sync.nothing.taken", { file: path.basename(file) })), data: { input: null, ...decoding, applied: [], changes: written.changes, ...timing() } };
520
579
  }
521
580
  // a send of the app waited in the inbox: written now (the app hears it through the bridge)
522
581
  // the app's files it wrote, with the records they are (the bridge's answer: `media`)
523
582
  const media = mediaWritten(written.changes, skipped);
524
- settleReceived(tree.root, file, { state: "written", input: input.id, kept: written.changes.filter((c) => c.kept).length, notWritten: notWrittenList(written.changes), skipped, media, ...(retracted.length ? { retracted } : {}) }, input.sync?.applied ?? []);
583
+ clocked("settle", () => settleReceived(tree.root, file, { state: "written", input: input.id, kept: written.changes.filter((c) => c.kept).length, notWritten: notWrittenList(written.changes), skipped, media, ...(retracted.length ? { retracted } : {}) }, input.sync?.applied ?? []));
525
584
  // each send of the app a little more history: packed in the background once it has grown
526
585
  compactSoon(tree.root, ctx.env);
527
586
  // a question to the person is no change of the research: counted as what it is
@@ -533,7 +592,7 @@ register({
533
592
  : ui(lang, "ui.sync.done", { n: changed, file: path.basename(file), input: input.id }), asks > 0 && changed > 0 ? ui(lang, "ui.sync.done.asked", { q: asks }) : undefined, ...skipped.map((x) => ui(lang, "ui.sync.skipped", { n: x.n, why: skippedWhy(x, lang) })), ...(proposed.length
534
593
  ? [`${proposed.length} change(s) of the user's or an imported family tree's values proposed, not written — the user decides (strom conflict list):`, ...proposed.map((x) => ` change ${x.n}: ${x.line}`)]
535
594
  : [])),
536
- data: { input: input.id, ...decoding, applied: input.sync?.applied ?? [], changes: written.changes, conflicts: syncConflicts(tree, input.id), ...(skipped.length ? { skipped } : {}), ...(proposed.length ? { proposed } : {}), ...(media.length ? { media } : {}), ...(retracted.length ? { retracted } : {}) },
595
+ data: { input: input.id, ...decoding, applied: input.sync?.applied ?? [], changes: written.changes, conflicts: syncConflicts(tree, input.id), ...(skipped.length ? { skipped } : {}), ...(proposed.length ? { proposed } : {}), ...(media.length ? { media } : {}), ...(retracted.length ? { retracted } : {}), ...timing() },
537
596
  };
538
597
  },
539
598
  }, {
@@ -1351,11 +1351,11 @@ register({
1351
1351
  const shown = dir ? ctx.display(dir) : `the inbox folder "${folder}"`;
1352
1352
  if (!awaits)
1353
1353
  return {
1354
- text: lines(written(tree), `waits ${waitSaid(tree, t)}`, `images of ${byBook.recordset} the user saves into ${shown} (each named by its number as the viewer counts it, 40.jpg) bring it back by themselves — as they are saved while the bridge runs, else at the next session's start; so does the user's answer`, `the numbers known: strom task wait ${t.id} --images ${byBook.recordset}:<numbers> --on "…" — the user sees which images and what is missing`, checkWaitLine(tree, t, s)),
1354
+ text: lines(written(tree), `waits ${waitSaid(tree, t)}`, `images of ${byBook.recordset} the user saves into ${shown} (each named by its number as the viewer counts it, 40.jpg, or with it in the name, __0040.jpg) bring it back by themselves — as they are saved while the bridge runs, else at the next session's start; so does the user's answer`, `the numbers known: strom task wait ${t.id} --images ${byBook.recordset}:<numbers> --on "…" — the user sees which images and what is missing`, checkWaitLine(tree, t, s)),
1355
1355
  data: { task: t, folder: dir, ...waitState(tree, t) },
1356
1356
  };
1357
1357
  return {
1358
- text: lines(written(tree), `the user saves images ${awaits.images} of ${b.id} into ${shown}, each named by its number (${parseImageList(awaits.images)[0]}.jpg; named otherwise, they are taken by their order when as many as asked for)`, "once all of them are saved the task comes back by itself — as they are saved while the bridge runs, else at the next session's start (strom media add --inbox --waiting takes them now); a part of them, it waits on and says which are missing; the user sees it in strom's menu (What waits) and the Strom app",
1358
+ text: lines(written(tree), `the user saves images ${awaits.images} of ${b.id} into ${shown}, each named by its number (${parseImageList(awaits.images)[0]}.jpg; the number in the name is enough, __0${parseImageList(awaits.images)[0]}.jpg; named otherwise, they are taken by their order when as many as asked for)`, "once all of them are saved the task comes back by itself — as they are saved while the bridge runs, else at the next session's start (strom media add --inbox --waiting takes them now); a part of them, it waits on and says which are missing; the user sees it in strom's menu (What waits) and the Strom app",
1359
1359
  // an archive only a person's browser goes to: what the agent's own browser would do there (spec 048 K5.2)
1360
1360
  ((a) => (a ? `its archive only through a person's browser — ${agentBrowserAdvice(ctx.env, detectAgent(ctx.env) ?? ctx.settings.agent(tree.config).value, a, t.id, b.id, false, tree.root)}` : undefined))(bookBrowserArchive(tree, b.url, s)), checkWaitLine(tree, t, s)),
1361
1361
  data: { task: t, folder: dir },
@@ -1,5 +1,6 @@
1
1
  // Domain write operations. Every change to the evidence goes through here,
2
2
  // under the tree lock, validated and sealed by Tree.put.
3
+ import { joinEmails } from "./contact.js";
3
4
  import { DirectionExists, UsageError } from "./errors.js";
4
5
  import { workOrder } from "./order.js";
5
6
  import { normalizeDate, reversedRange } from "./gdate.js";
@@ -1116,9 +1117,12 @@ export function mergePersons(tree, keepId, otherId, reason) {
1116
1117
  const refs = [...(keep.refs ?? []), ...(other.refs ?? []).filter((r) => !(keep.refs ?? []).some((k) => k.system === r.system && k.id === r.id))];
1117
1118
  // the IDs of family trees: both records', the other's as not come of its import (its values are the kept one's now)
1118
1119
  const originalIds = joinIds(keep.originalIds, mergedAway(other.originalIds)).list;
1120
+ // the contact (spec 134 U11): both persons' e-mails, each once
1121
+ const emails = joinEmails(keep.contact?.emails, other.contact?.emails);
1119
1122
  const why = reason.trim();
1120
1123
  const merged = {
1121
1124
  ...keep,
1125
+ ...(emails.length ? { contact: { ...keep.contact, emails } } : {}),
1122
1126
  names,
1123
1127
  sex: keep.sex === "U" ? other.sex : keep.sex,
1124
1128
  events: [...keep.events, ...other.events],
@@ -3,11 +3,14 @@
3
3
  // its original's hash (_STROM_SHA, the original came by PUT /media) or else by the hash of the bytes the send carries;
4
4
  // those bytes — the working copy the app shows — are kept exactly as they came in the shared store, under their own
5
5
  // hash, while the file is read (P8): one image in memory at a time, a hash kept already never written again.
6
+ // Spec 133: a file the research has may come by reference instead (_STROM_DATA <sha> where FILE data:… would be — the
7
+ // same file as if those bytes had come), and the research's excerpt with no FILE at all (its data is never read).
6
8
  import crypto from "node:crypto";
7
9
  import fs from "node:fs";
8
10
  import path from "node:path";
9
11
  import { MATERIAL_KINDS } from "./model.js";
10
12
  import { sharedMediaPath } from "./media.js";
13
+ import { recordsBySha } from "./shaindex.js";
11
14
  import { importDate } from "./import.js";
12
15
  import { formatOf, imageSize } from "../image/index.js";
13
16
  import { children, val } from "../gedcom/parse.js";
@@ -60,6 +63,58 @@ export function dataUrlBytes(value) {
60
63
  return undefined;
61
64
  return { ...(head[0] ? { mime: head[0] } : {}), bytes };
62
65
  }
66
+ /** A working copy as its bytes make it: the type its data URL says (else its content's, else FORM's), its size, its extension. */
67
+ function workingOfBytes(sha, bytes, said, form) {
68
+ const format = formatOf(bytes);
69
+ const mime = (said && said !== "application/octet-stream" ? said : undefined) ?? BY_FORMAT[format] ?? mimeOfForm(form) ?? "application/octet-stream";
70
+ const ext = EXT[mime] ?? (BY_FORMAT[format] ? EXT[BY_FORMAT[format]] : undefined) ?? ".bin";
71
+ const size = mime.startsWith("image/") ? imageSize(bytes) : undefined;
72
+ return { sha, mime, bytes: bytes.length, ...(size ? size : {}), ext };
73
+ }
74
+ /** The file of these bytes in the shared store (media/ab/cd/<sha>.<any extension>), never one half written. */
75
+ export function storedBytes(store, sha) {
76
+ if (!SHA.test(sha))
77
+ return undefined;
78
+ const dir = path.dirname(sharedMediaPath(store, sha, ""));
79
+ let names;
80
+ try {
81
+ names = fs.readdirSync(dir);
82
+ }
83
+ catch {
84
+ return undefined;
85
+ }
86
+ const name = names.find((n) => n.startsWith(`${sha}.`) && !n.endsWith(".part") && !n.endsWith(".tmp"));
87
+ return name ? path.join(dir, name) : undefined;
88
+ }
89
+ /**
90
+ * The bytes of a file a send names by its hash (_STROM_DATA, spec 133): in the shared store (a working copy, an image, an
91
+ * original that came by PUT /media), else the research's own file of that content (inputs/, held in git) — the same
92
+ * places POST /media/known answers from. None: the research does not have it.
93
+ */
94
+ export function mediaRefFile(tree, store, sha) {
95
+ const inStore = store ? storedBytes(store, sha) : undefined;
96
+ if (inStore || !tree)
97
+ return inStore;
98
+ // a file deleted for good (core/materialdelete.ts) is none
99
+ const own = recordsBySha(tree, "input", sha).find((x) => x.file?.startsWith("inputs/") && x.retracted?.reason !== "deleted");
100
+ const file = own ? path.join(tree.root, own.file) : undefined;
101
+ return file && fs.existsSync(file) ? file : undefined;
102
+ }
103
+ /** The working copy of a file named by its hash, from the bytes the research has of it (the shared store, its own files). */
104
+ export function mediaResolver(tree, store) {
105
+ return (sha, form) => {
106
+ const file = mediaRefFile(tree, store, sha);
107
+ if (!file)
108
+ return undefined;
109
+ try {
110
+ // the type FORM says stands where the data URL's would (the app writes FORM from it)
111
+ return workingOfBytes(sha, fs.readFileSync(file), mimeOfForm(form), form);
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ };
117
+ }
63
118
  /** Bytes kept in the shared store under their hash: never written again when there; written whole or not at all. */
64
119
  export function keepBytes(store, sha, ext, bytes) {
65
120
  const dest = sharedMediaPath(store, sha, ext);
@@ -81,12 +136,19 @@ export class MediaReader {
81
136
  problems;
82
137
  objects;
83
138
  store;
139
+ resolve;
84
140
  note;
85
141
  /** Read already (the bytes of a data URL hashed once: the same text of it is the same file). */
86
142
  seen = new Map();
143
+ /**
144
+ * `store`: the shared store the bytes a send carries are kept in (and a file named by its hash is found in); `resolve`:
145
+ * how a file named by its hash is found otherwise (the research's own files). Neither: a read that keeps nothing (the
146
+ * plan) — a file named by its hash is the file of that hash, as the send says it.
147
+ */
87
148
  constructor(records, o) {
88
149
  this.objects = new Map(records.filter((r) => r.tag === "OBJE" && r.xref).map((r) => [r.xref, r]));
89
150
  this.store = o.store;
151
+ this.resolve = o.resolve;
90
152
  this.problems = o.problems;
91
153
  this.note = o.note;
92
154
  }
@@ -111,6 +173,8 @@ export class MediaReader {
111
173
  const formNode = nodeOf("FORM");
112
174
  const form = formNode?.value.trim().toLowerCase() || undefined;
113
175
  let working;
176
+ // the bytes by reference (spec 133): the hash of the data URL's bytes the research has, where FILE data:… would be
177
+ const byRef = !/^data:/i.test(value) ? field("_STROM_DATA")?.trim().toLowerCase() : undefined;
114
178
  if (/^data:/i.test(value)) {
115
179
  const known = this.seen.get(value);
116
180
  if (known === null)
@@ -123,20 +187,37 @@ export class MediaReader {
123
187
  return { unreadable: shownName ?? "?" };
124
188
  }
125
189
  const sha = crypto.createHash("sha256").update(got.bytes).digest("hex");
126
- const format = formatOf(got.bytes);
127
- const mime = (got.mime && got.mime !== "application/octet-stream" ? got.mime : undefined) ?? BY_FORMAT[format] ?? mimeOfForm(form) ?? "application/octet-stream";
128
- const ext = EXT[mime] ?? (BY_FORMAT[format] ? EXT[BY_FORMAT[format]] : undefined) ?? ".bin";
129
- const size = mime.startsWith("image/") ? imageSize(got.bytes) : undefined;
130
- working = { sha, mime, bytes: got.bytes.length, ...(size ? size : {}), ext };
190
+ working = workingOfBytes(sha, got.bytes, got.mime, form);
131
191
  if (this.store)
132
- keepBytes(this.store, sha, ext, got.bytes);
192
+ keepBytes(this.store, sha, working.ext, got.bytes);
133
193
  this.seen.set(value, working);
134
194
  }
135
195
  }
196
+ else if (byRef && SHA.test(byRef)) {
197
+ // the original sent as it is: nothing more to find (as its bytes would be: no working copy of its own)
198
+ if (byRef !== original) {
199
+ const at = `ref:${byRef}`;
200
+ const known = this.seen.get(at);
201
+ if (known === null)
202
+ return { unreadable: shownName ?? "?" };
203
+ working = known;
204
+ if (!working) {
205
+ // a reader that keeps files finds them (none found: said, never a record of bytes nobody has); one that keeps
206
+ // nothing takes the file as the send names it — its hash, the type FORM says — the same key, record and places
207
+ const mime = mimeOfForm(form) ?? "application/octet-stream";
208
+ working = this.resolve ? this.resolve(byRef, form) : this.store ? mediaResolver(undefined, this.store)(byRef, form) : { sha: byRef, mime, bytes: 0, ext: EXT[mime] ?? ".bin" };
209
+ this.seen.set(at, working ?? null);
210
+ if (!working)
211
+ return { unreadable: shownName ?? "?" };
212
+ }
213
+ }
214
+ }
215
+ else if (byRef)
216
+ return { unreadable: shownName ?? "?" };
136
217
  else if (!original || !SHA.test(original))
137
218
  return undefined;
138
219
  const orig = original && SHA.test(original) ? original : undefined;
139
- const key = orig ?? working.sha;
220
+ const key = orig ?? working?.sha ?? byRef;
140
221
  const typeWord = val(formNode, "TYPE")?.toLowerCase();
141
222
  const kind = MATERIAL_KINDS.includes(typeWord ?? "") ? typeWord : undefined;
142
223
  const rawDate = field("_DATE")?.normalize("NFC");
@@ -187,3 +268,122 @@ export function recordOfFile(inputs, f) {
187
268
  }
188
269
  return undefined;
189
270
  }
271
+ /** How many unknown hashes a refusal names (409 sync.media-ref-unknown). */
272
+ export const MEDIA_REF_UNKNOWN_MAX = 50;
273
+ /**
274
+ * The OBJE of a send's text, line by line (no GEDCOM tree built: a send of 100 MB is mostly its data): how many name
275
+ * their bytes by reference, are excerpts without FILE, carry their data — and the hashes named, in their order.
276
+ */
277
+ export function mediaRefsOf(text) {
278
+ const out = { dataRefs: 0, excerptsWithoutFile: 0, withData: 0, refs: [] };
279
+ const seen = new Set();
280
+ let cur;
281
+ const close = () => {
282
+ if (!cur)
283
+ return;
284
+ if (cur.data)
285
+ out.withData++;
286
+ if (cur.excerpt) {
287
+ if (!cur.file)
288
+ out.excerptsWithoutFile++;
289
+ }
290
+ else if (!cur.file && cur.ref !== undefined) {
291
+ out.dataRefs++;
292
+ if (!seen.has(cur.ref)) {
293
+ seen.add(cur.ref);
294
+ out.refs.push(cur.ref);
295
+ }
296
+ }
297
+ cur = undefined;
298
+ };
299
+ const n = text.length;
300
+ let i = 0;
301
+ while (i < n) {
302
+ let end = text.indexOf("\n", i);
303
+ if (end < 0)
304
+ end = n;
305
+ let p = i;
306
+ i = end + 1;
307
+ // the line: level, an xref, its tag, its value (a BOM, spaces, a CR at its end skipped)
308
+ while (p < end && (text.charCodeAt(p) === 0xfeff || text.charCodeAt(p) === 32 || text.charCodeAt(p) === 9))
309
+ p++;
310
+ let level = -1;
311
+ while (p < end) {
312
+ const c = text.charCodeAt(p);
313
+ if (c < 48 || c > 57)
314
+ break;
315
+ level = (level < 0 ? 0 : level * 10) + c - 48;
316
+ p++;
317
+ }
318
+ if (level < 0)
319
+ continue;
320
+ // a line under the file's data (CONC) or deeper: nothing to look at
321
+ if (cur && level > cur.level + 1)
322
+ continue;
323
+ if (cur && level <= cur.level)
324
+ close();
325
+ while (p < end && text.charCodeAt(p) === 32)
326
+ p++;
327
+ if (text.charCodeAt(p) === 64 /* @ */) {
328
+ const at = text.indexOf(" ", p);
329
+ p = at < 0 || at > end ? end : at;
330
+ while (p < end && text.charCodeAt(p) === 32)
331
+ p++;
332
+ }
333
+ let t = p;
334
+ while (t < end && text.charCodeAt(t) !== 32 && text.charCodeAt(t) !== 13)
335
+ t++;
336
+ const tag = text.slice(p, t);
337
+ const value = () => text.slice(t + 1, end).replace(/\r$/, "").trim();
338
+ if (tag === "OBJE") {
339
+ // a pointer (1 OBJE @M1@) is its record's: counted there
340
+ if (!value().startsWith("@"))
341
+ cur = { level, file: false, data: false, excerpt: false };
342
+ continue;
343
+ }
344
+ if (!cur || level !== cur.level + 1)
345
+ continue;
346
+ if (tag === "FILE") {
347
+ cur.file = true;
348
+ cur.data = /^data:/i.test(text.slice(t + 1, Math.min(end, t + 6)));
349
+ }
350
+ else if (tag === "_STROM_KIND")
351
+ cur.excerpt = value().toLowerCase() === "excerpt";
352
+ else if (tag === "_STROM_DATA")
353
+ cur.ref = value().toLowerCase().slice(0, 64);
354
+ }
355
+ close();
356
+ return out;
357
+ }
358
+ /**
359
+ * The check of a send before the bridge takes it (spec 133 §1.4, §1.5): what it carries of its files, and the hashes it
360
+ * names by reference the research cannot find (the shared store, the research's own files — `mediaRefFile`); any of
361
+ * them: the whole send is refused (409 sync.media-ref-unknown), the app sends it again with the data. An excerpt with no
362
+ * FILE is never unknown. The research is opened only when a hash is not in the store.
363
+ */
364
+ export function checkMediaRefs(text, research) {
365
+ const { refs, ...counts } = mediaRefsOf(text);
366
+ const unknown = [];
367
+ let tree;
368
+ let opened = false;
369
+ const treeOf = () => {
370
+ if (!opened) {
371
+ opened = true;
372
+ try {
373
+ tree = typeof research.tree === "function" ? research.tree() : research.tree;
374
+ }
375
+ catch {
376
+ tree = undefined;
377
+ }
378
+ }
379
+ return tree;
380
+ };
381
+ for (const sha of refs) {
382
+ if (unknown.length >= MEDIA_REF_UNKNOWN_MAX)
383
+ break;
384
+ const found = SHA.test(sha) && ((research.store ? storedBytes(research.store, sha) : undefined) ?? mediaRefFile(treeOf(), undefined, sha));
385
+ if (!found)
386
+ unknown.push(sha);
387
+ }
388
+ return { unknown, ...counts };
389
+ }
@@ -517,6 +517,13 @@ export function changeLines(tree, ops, subject, lang, was, tasks) {
517
517
  say(phrase(lang, o.op === "streetplace.fix" ? "log.streetplace.fix" : "log.streetplace.unfix", { n }));
518
518
  continue;
519
519
  }
520
+ // the e-mails of residences that were contacts moved to the persons' contacts by strom's fix, or put back
521
+ // (quality/contact-residences.json)
522
+ if (o.op === "contact.fix" || o.op === "contact.unfix") {
523
+ const n = /: (\d+) in /u.exec(o.summary)?.[1] ?? String(o.targets.length);
524
+ say(phrase(lang, o.op === "contact.fix" ? "log.contact.fix" : "log.contact.unfix", { n }));
525
+ continue;
526
+ }
520
527
  // disagreements with the user's own edits an agent decided, opened again for the user by strom's fix, or closed again
521
528
  // (quality/edit-decisions.json)
522
529
  if (o.op === "editdecision.fix" || o.op === "editdecision.unfix") {