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
package/dist/core/live.js CHANGED
@@ -71,6 +71,10 @@
71
71
  // says a name's status, confirmation and verification under NAME (2 _STROM_EID P….N): the app
72
72
  // offers Verify (POST /verify {fact: P….N}) and Confirm against the scan (POST /facts/confirm
73
73
  // {fact: P….N}) at the name of a person's identity — the confirmation in an archive too.
74
+ // person.contact (spec 134 U11, every app, an archive too): a person's contact (their e-mails)
75
+ // is the research's — strom sync and an app's handover read it as 1 RESI / 2 EMAIL, as the
76
+ // app's older residence of nothing but a note "E-mail: …" and as 1 EMAIL, and /tree.ged
77
+ // writes it as 1 RESI / 2 EMAIL (at most three to a RESI), no date, status or mark of strom's.
74
78
  // GET <token>/status/<part> one of those parts: {part, rev, head, …its fields as /status carries them}; 404
75
79
  // status.part for another name.
76
80
  // A queue item off the lines of a research with several (core/offline.ts) says offLine:
@@ -98,6 +102,8 @@
98
102
  // is tens of MB) — one making at a time, the asks for the same file wait for it together, /status and the rest answer meanwhile;
99
103
  // made once for each head and variant (the app's version, links, images' settings) and kept on
100
104
  // disk (.strom/cache/live-ged: a bridge started again gives it at once); X-Strom-Head its head.
105
+ // A person's contact (feature person.contact): 1 RESI with 2 EMAIL lines alone (three at most,
106
+ // then another RESI) — no event of the research; read back by strom sync as the contact.
101
107
  // ?stale=1 (feature ged.stale): the last one made of the variant at once, though the research
102
108
  // changed since (X-Strom-Stale: 1, X-Strom-Head-Now), the new one told by the event change. While
103
109
  // the app follows (/events), a change is told once the tree of its head is made (at most 45 s).
@@ -156,7 +162,11 @@
156
162
  // inbox to be shown and written on the user's word (strom sync) — nothing of the
157
163
  // research changes; /status says what waits there (inbox) and how each send went (sends);
158
164
  // ?media=app: the send carries every file of its tree — a place of one the app was given with
159
- // the files (GET /tree.ged?media=app of its _STROM_HEAD) and no longer has is taken off
165
+ // the files (GET /tree.ged?media=app of its _STROM_HEAD) and no longer has is taken off.
166
+ // Files by reference (spec 133, feature sync.mediaRef): `_STROM_DATA <sha>` where FILE data:…
167
+ // would be, the research's excerpt with no FILE; a hash the research cannot find (the shared
168
+ // store, its own files) refuses the whole send before anything is kept: 409
169
+ // {ok: false, code: sync.media-ref-unknown, error, shas: [≤ 50]} — the app sends it with the data
160
170
  // POST <token>/cancel …or says it sends nothing ({"reason": "unchanged" | "cancelled" | "no-tree"})
161
171
  // GET <token>/media/<sha256> whether the research has a file of that content (an original the app would send);
162
172
  // ?file=1: the file itself (the original, for the app's viewer)
@@ -269,12 +279,22 @@
269
279
  // the app takes head as its version only when parent is the head it knew
270
280
  // GET <token>/media/<sha256>?thumb=128|256|512 a small JPEG preview of a file (core/thumbs.ts, kept in
271
281
  // .strom/thumbs): 400 thumb.size, 404, 410 media.gone, 415 thumb.type (none of this kind here)
282
+ // PUT <token>/lists/<id> a list of people material is sent to ({name, kind: fixed|auto|work, rule?: the rule as the
283
+ // app says it, ruleData?, persons: [P…] as they are now, missing?: how many of its people the
284
+ // research has not got, at?}): kept by the bridge (.strom/lists/<id>.json; the same id again
285
+ // replaces it) until a file names it; {list, persons, unknown}. 400 list.bad-body, 413
286
+ // list.large, 403 app.only
272
287
  // PUT <token>/media/<sha256> an original from the app, unchanged (the body; X-Strom-Name, -Person, -Source,
273
288
  // -Region, -Note): streamed to disk, its hash checked, kept outside git
274
289
  // (strom media original) — of a source an image, else material of people; a task for the
275
290
  // agent (an intake task, a task to read the scan of a source) only with intake.auto on, else
276
291
  // the file waits in the material: {input} or {known, added?} with no task (spec 130 K1.3);
277
292
  // X-Strom-Batch, -Path (and -Zip: 1, a ZIP unpacked here): one file of a batch
293
+ // X-Strom-List-Ref: <id> — sent to a list of people (spec 137, media.list) the app put
294
+ // first (below): kept on the input (Input.list, its people as sent in notes/lists/), up to 50
295
+ // of its people the input's people too; with -Source (media.list.source) kept on the scan
296
+ // (Media.list), up to 50 of its people those of its task to read it; not with -Task, -Read,
297
+ // -Batch; 404 media.no-list {list} for a list not sent
278
298
  // X-Strom-Family: F… (with commas; X-Strom-Person beside it too) — a couple's original
279
299
  // (spec 108 V9, accepts.media.family): material of both partners (Input.families) with an
280
300
  // intake task as for a person's with intake.auto on (put aside in an archive); media.bad-header for no F…, 404
@@ -300,7 +320,8 @@
300
320
  // after it failed. Without Prefer: written before the answer, as before
301
321
  // POST <token>/media/known what the research has of many files at once ({shas: [SHA-256] (at most 5000)},
302
322
  // feature media.known): {known: {<sha>: {id, kind, mime, bytes, here} | {queued: true} |
303
- // null}}; 413 media.known-many {max}, 400 media.known-body. Read only. GET /media/<sha> of a
323
+ // null}} — a working copy of a file of the app's tree by its own hash too, while its bytes are
324
+ // in the shared store (spec 133); 413 media.known-many {max}, 400 media.known-body. Read only. GET /media/<sha> of a
304
325
  // queued file: 404 {known: null, queued: true}
305
326
  // POST <token>/batch/<id>/done the batch is whole ({name, files, person, note, sort?: true|false}): with
306
327
  // intake.auto on its files become sorting tasks, off (the default, spec 130) they wait in the
@@ -760,7 +781,7 @@ import { endWork, excerptAnswer, excerptOnThread, fixesOnThread, gedOnThread, ge
760
781
  import { IMAGE_MIME, IMAGE_SHA, imageFile, readImage } from "./liveimages.js";
761
782
  import { markServedWithMedia, treeMediaFile } from "./treemedia.js";
762
783
  import { isStatusPart, splitStatus, StatusKeeper, STATUS_PARTS } from "./livestatus.js";
763
- import { adoptedAt, notWrittenList, adoptedEmpty, adoptionWait, noteAdoptAsked, markSentAgain, undoneSend, undoneSince, failReceived, inboxTrees, markAdopted, noteAdoptFailed, noteNothingSent, pendingAdoption, receiveAdopted, receivedAll, receivedPending, receiveTree, recentSends, stampAppVersion, syncConflicts, SYNC_INBOX, SYNC_MAX_BYTES, namesOf } from "./sync.js";
784
+ import { adoptedAt, notWrittenList, adoptedEmpty, adoptionWait, noteAdoptAsked, markSentAgain, undoneSend, undoneSince, failReceived, inboxTrees, markAdopted, noteAdoptFailed, noteNothingSent, pendingAdoption, receiveAdopted, receivedAll, receivedPending, receiveTree, recentSends, refuseReceived, stampAppVersion, syncConflicts, SYNC_INBOX, SYNC_MAX_BYTES, namesOf } from "./sync.js";
764
785
  import { isArchive, modeOf, settleArchive } from "./mode.js";
765
786
  import { actsAsArchive, kindOf, settleWaiting, stateOf } from "./state.js";
766
787
  import { forStory } from "./stories.js";
@@ -777,11 +798,13 @@ import { PROFILES } from "../agents/profiles.js";
777
798
  import { ui } from "../cli/ui.js";
778
799
  import { DISK_FULL, EXIT, isDiskFull, StromError } from "./errors.js";
779
800
  import { acquireLock, liveHolder } from "./lock.js";
780
- import { checkAsked, checkEdit, material, MATERIAL_MOST_EDIT, MATERIAL_MOST_FILES, MATERIAL_MOST_PEOPLE, materialUses, peopleOf, workingCopyOf } from "./material.js";
801
+ import { checkAsked, checkEdit, material, MATERIAL_MOST_EDIT, MATERIAL_MOST_FILES, MATERIAL_MOST_PEOPLE, materialUses, peopleOf, workingCopyBySha, workingCopyOf } from "./material.js";
802
+ import { checkMediaRefs } from "./appmedia.js";
781
803
  import { checkDeleteConfirm, checkRetractWith, deleteConfirm, DELETE_MOST_FILES, deleteImpacts, deleteSourceImpacts, refuseLiveSources } from "./materialdelete.js";
782
804
  import { checkRetractConfirm, keepable, restorable, RETRACT_MOST, retractConfirm, retractImpacts } from "./sourceretract.js";
783
805
  import { cachedThumb, THUMB_SIZES } from "./thumbs.js";
784
806
  import { checkOriginalMeta, cleanIncoming, freeBytes, knownOriginal, materialWaiting, originalMax, ORIGINAL_RESERVE, ORIGINAL_TYPES, parseRegion } from "./originals.js";
807
+ import { checkSentList, keepSentList, LIST_BODY_MAX, LIST_ID, readSentList } from "./lists.js";
785
808
  import { BATCH_ID, batchEstimate, batchLimits, batchPath, batchStatus, idleBatches, readBatch } from "./batches.js";
786
809
  /** New images for the app, made for at most so long when the tree changed (the rest the next time). */
787
810
  const LIVE_IMAGES_MS = 20_000;
@@ -898,7 +921,7 @@ const REGION_ID = /^[a-z0-9][a-z0-9-]{0,23}$/u;
898
921
  function placeOk(v) {
899
922
  return typeof v === "string" && !!v.trim() && v.length <= 300 && !/[\u0000-\u001f\u007f]/u.test(v);
900
923
  }
901
- const APP_WRITES = new Set(["sync", "adopt", "media", "batch", "waiting", "group", "material", "read", "history", "experiments", "quality", "places", "directions", "offline", "queue", "census", "intake"]);
924
+ const APP_WRITES = new Set(["sync", "adopt", "media", "lists", "batch", "waiting", "group", "material", "read", "history", "experiments", "quality", "places", "directions", "offline", "queue", "census", "intake"]);
902
925
  /** A file refused (its error's code): what the bridge says of it. */
903
926
  const REFUSED = {
904
927
  "tree.other-research": "ui.sync.bridge.other",
@@ -920,7 +943,9 @@ function said(lang, key, params = {}) {
920
943
  * -Path, -Name, -Note, -Task)
921
944
  * - `media.bad-region` 400 {region} — X-Strom-Region is no part of an image
922
945
  * - `media.no-person` 404 {person} — no such person in the research; `media.no-family` 404 {family} — no such couple
923
- * (X-Strom-Family); `media.no-source` 404 {source} — no such source
946
+ * (X-Strom-Family); `media.no-source` 404 {source} — no such source; `media.no-list` 404 {list} — no list of that
947
+ * mark sent (X-Strom-List-Ref: PUT lists/<id> first)
948
+ * - `list.bad-body` 400, `list.large` 413 — PUT lists/<id>: a body that is no list, a list too large
924
949
  * - `media.no-shared` 500 — the research has no shared folder for files (strom setup)
925
950
  * - `media.large` 413 {mb} (and `max`) — larger than the research takes; `media.full` 507 (and `free`) — no room
926
951
  * (these two: `error` in the research's language, `text` English — said() above)
@@ -1858,9 +1883,11 @@ export function tagMatches(req, tag) {
1858
1883
  .map((t) => t.trim().replace(/^W\//u, ""))
1859
1884
  .some((t) => t === "*" || t === tag);
1860
1885
  }
1886
+ /** A send naming by reference a file the research cannot find (spec 133 §1.4): refused whole, 409. */
1887
+ const MEDIA_REF_UNKNOWN = "sync.media-ref-unknown";
1861
1888
  /** How many hashes POST /media/known takes at once. */
1862
1889
  export const MEDIA_KNOWN_MAX = 5000;
1863
- export const BRIDGE_FEATURES = ["sync.again", "sync.undoneSince", "sync.takenBack", "sync.conflictEdit", "sync.since", "sync.ids", "family.noCouple", "family.alone", "adopt.transfer", "adopt.empty", "material.list", "person.titles", "media.codes", "hypothesis.links", "status.recent", "spend.readers", "hypothesis.intree", "archive.permission", "task.check", "waiting.groups", "waiting.sent", "waiting.note", "batch.kept", "live.end", "whats.new", "terminal.choice", "person.marriedSurname", "phone", "read.now", "read.sync", "excerpt.get", "log.sources", "material.assign", "material.thumb", "seal.foreign", "tree.state", "disk.full", "tree.notDownloaded", "sync.removed", "tree.kind", "experiments", "experiments.off", "experiments.link", "experiments.split", "history.events", "history.hide", "experiments.pace", "history.first", "history.regions", "history.hide.all", "history.skip", "history.map", "history.delete", "history.delete.restore", "stories.history", "history.place", "surnames.suggest", "surnames.read", "lineage.read", "duplicates.judge", "quality.dismiss", "quality.read", "person.primary", "fixes.list", "fixes.towns", "history.back", "places.identify", "places.answer", "places.undo", "tasks.offLine", "status.busy", "history.kinds", "history.align", "places.nameKinds", "directions.edit", "directions.order", "directions.found", "directions.people", "directions.places", "offLine.branches", "queue.own", "story.sources", "queue.page", "status.parts", "waiting.answer", "browser.state", "working.place", "working.family", "working.helps", "hypotheses.decide", "sources.confirm", "read.sourceTask", "read.sourceTask.unsure", "read.choose", "read.choices.now", "read.source", "read.sourceEntry", "read.blindText", "read.kinds", "read.variantKind", "read.readerState", "live.idle", "live.stop", "live.start", "sources.proposal", "sources.proposal.undo", "origin", "origin.ids", "verify", "verify.bulk", "facts.confirm", "verify.stop", "ged.stale", "facts.confirm.value", "ged.etag", "ged.imagesByHash", "hypothesis.decide.link", "hypotheses.accept.link", "sources.fields", "sources.split", "queue.search", "queue.next", "work.link", "run.tasks", "queue.kind", "work.tasks", "verify.tryFirst", "event.share", "citations.order", "sync.notWritten.codes", "citations.main", "citations.remove", "books", "media.app", "material.links", "material.edit", "material.uses", "material.sort", "tasks.audit", "handoffs", "material.sourceOf", "material.left", "material.sameAs", "material.sortRun", "material.delete", "inbox.aside", "source.retract", "material.trees", "census", "name-status", "task.holds", "archive.holds", "media.queued", "media.known", "intake.auto", "run.lines", "run.agents", "run.stop", "run.limit", "directions.move"];
1890
+ export const BRIDGE_FEATURES = ["sync.again", "sync.undoneSince", "sync.takenBack", "sync.conflictEdit", "sync.since", "sync.ids", "family.noCouple", "family.alone", "adopt.transfer", "adopt.empty", "material.list", "person.titles", "media.codes", "hypothesis.links", "status.recent", "spend.readers", "hypothesis.intree", "archive.permission", "task.check", "waiting.groups", "waiting.sent", "waiting.note", "batch.kept", "live.end", "whats.new", "terminal.choice", "person.marriedSurname", "phone", "read.now", "read.sync", "excerpt.get", "log.sources", "material.assign", "material.thumb", "seal.foreign", "tree.state", "disk.full", "tree.notDownloaded", "sync.removed", "tree.kind", "experiments", "experiments.off", "experiments.link", "experiments.split", "history.events", "history.hide", "experiments.pace", "history.first", "history.regions", "history.hide.all", "history.skip", "history.map", "history.delete", "history.delete.restore", "stories.history", "history.place", "surnames.suggest", "surnames.read", "lineage.read", "duplicates.judge", "quality.dismiss", "quality.read", "person.primary", "fixes.list", "fixes.towns", "history.back", "places.identify", "places.answer", "places.undo", "tasks.offLine", "status.busy", "history.kinds", "history.align", "places.nameKinds", "directions.edit", "directions.order", "directions.found", "directions.people", "directions.places", "offLine.branches", "queue.own", "story.sources", "queue.page", "status.parts", "waiting.answer", "browser.state", "working.place", "working.family", "working.helps", "hypotheses.decide", "sources.confirm", "read.sourceTask", "read.sourceTask.unsure", "read.choose", "read.choices.now", "read.source", "read.sourceEntry", "read.blindText", "read.kinds", "read.variantKind", "read.readerState", "live.idle", "live.stop", "live.start", "sources.proposal", "sources.proposal.undo", "origin", "origin.ids", "verify", "verify.bulk", "facts.confirm", "verify.stop", "ged.stale", "facts.confirm.value", "ged.etag", "ged.imagesByHash", "hypothesis.decide.link", "hypotheses.accept.link", "sources.fields", "sources.split", "queue.search", "queue.next", "work.link", "run.tasks", "queue.kind", "work.tasks", "verify.tryFirst", "event.share", "citations.order", "sync.notWritten.codes", "citations.main", "citations.remove", "books", "media.app", "material.links", "material.edit", "material.uses", "material.sort", "tasks.audit", "handoffs", "material.sourceOf", "material.left", "material.sameAs", "material.sortRun", "material.delete", "inbox.aside", "source.retract", "material.trees", "census", "name-status", "task.holds", "archive.holds", "media.queued", "media.known", "intake.auto", "run.lines", "run.agents", "run.stop", "run.limit", "directions.move", "sync.mediaRef", "person.contact", "media.list", "media.list.source"];
1864
1891
  /** What only a research with its agent here does (accepts.read: none in an archive, nor where it waits for its agent). */
1865
1892
  const AGENT_FEATURES = new Set(["material.sort", "run.lines", "run.agents", "run.stop", "run.limit", "directions.move"]);
1866
1893
  const withoutAgent = (features) => features.filter((f) => !AGENT_FEATURES.has(f));
@@ -2890,6 +2917,14 @@ export function saidAppVersion(req) {
2890
2917
  const said = (Array.isArray(header) ? header[0] : header)?.trim() || query?.trim();
2891
2918
  return said && isAppVersion(said) ? said : undefined;
2892
2919
  }
2920
+ /**
2921
+ * The folder a new research of this computer is made in (strom.trees, else the home: `strom init`'s), for the app to show
2922
+ * where a research of a copy of its tree would go (spec 139 K5.4) — only a text to show; none where nothing is set up.
2923
+ */
2924
+ function treesRootOf(env, settings = new Settings(env, {})) {
2925
+ const at = settings.trees()?.value;
2926
+ return at ? { treesRoot: at } : {};
2927
+ }
2893
2928
  /** What the app shows beside the tree. */
2894
2929
  /**
2895
2930
  * /status worked out (on the bridge's thread of /status, core/livestatus.ts: it reads the whole research — never on the
@@ -2906,6 +2941,7 @@ export function status(root, env, version, seen) {
2906
2941
  ...channelOf(env),
2907
2942
  tree: { id: config?.id, name: config?.name, lang: config?.lang },
2908
2943
  path: root,
2944
+ ...treesRootOf(env),
2909
2945
  locked: { code: refused.code, reason: refused.message, way: refused.hint, ...(refused.params ?? {}) },
2910
2946
  live: liveState(env),
2911
2947
  links: links(env),
@@ -2946,6 +2982,7 @@ export function status(root, env, version, seen) {
2946
2982
  // what the research is (an archive, a research, one waiting for its agent) — the app says it beside the tree
2947
2983
  tree: { id: tree.config.id, name: tree.config.name, lang: tree.lang, state: stateOf(tree), kind: kindOf(tree) },
2948
2984
  path: root,
2985
+ ...treesRootOf(env, settings),
2949
2986
  // sealed on this computer (writing works), or on another (its folder brought here, strom's settings gone): the
2950
2987
  // app's writes are refused with seal.foreign until the person takes it over (strom seal adopt, the menu, the link seal)
2951
2988
  seal: tree.key ? "here" : "elsewhere",
@@ -3913,6 +3950,10 @@ export function serveLive(root, env) {
3913
3950
  receive(req, res, origin, "adopt");
3914
3951
  return;
3915
3952
  }
3953
+ if (req.method === "PUT" && t === token && what === "lists" && sub && !act) {
3954
+ listPut(req, res, origin, decodeURIComponent(sub));
3955
+ return;
3956
+ }
3916
3957
  if (req.method === "PUT" && t === token && what === "media") {
3917
3958
  // the warm writer started as the original comes (it loads while the bytes come)
3918
3959
  writer.warm();
@@ -4478,6 +4519,32 @@ export function serveLive(root, env) {
4478
4519
  // strom holding it longer than a writer waits): the send is tried again a while later, not left waiting for ever.
4479
4520
  let writing;
4480
4521
  let retryAt;
4522
+ const secs = (ms) => (!ms ? "0 s" : ms < 1000 ? `${(ms / 1000).toFixed(2)} s` : `${(ms / 1000).toFixed(1)} s`);
4523
+ const parts = (p) => p && Object.keys(p).length ? ` (${["ours", "given", "since", "after", "mend", "rest"].filter((k) => p[k] !== undefined).map((k) => `${k} ${secs(p[k])}`).join(", ")})` : "";
4524
+ const noteSend = (c) => {
4525
+ if (c.said || c.writing)
4526
+ return;
4527
+ c.said = true;
4528
+ const at = [
4529
+ c.body !== undefined ? `body ${secs(c.body)}` : undefined,
4530
+ c.decode !== undefined ? `decode ${secs(c.decode)}` : undefined,
4531
+ c.undone !== undefined ? `undone ${secs(c.undone)}` : undefined,
4532
+ c.got?.ids !== undefined ? `known ids+file ${secs(c.got.ids)}` : undefined,
4533
+ c.got?.plan !== undefined ? `plan ${secs(c.got.plan)}${parts(c.got.planParts)}` : undefined,
4534
+ c.child !== undefined
4535
+ ? `writer ${secs(c.child)}${c.phases ? ` (read ${secs(c.phases.read)}, plan ${secs(c.phases.plan)}${parts(c.planParts)}, plans ${c.plans ?? 0}, lock ${secs(c.phases.lock)}, apply ${secs(c.phases.apply)}, settle ${secs(c.phases.settle)})` : ""}`
4536
+ : undefined,
4537
+ c.media ? `files by reference ${c.media.dataRefs}, excerpts without FILE ${c.media.excerptsWithoutFile}, with data ${c.media.withData}` : undefined,
4538
+ c.answer ? `answered ${c.answer.code} at ${secs(c.answer.at)}` : "answered before",
4539
+ ].filter(Boolean);
4540
+ noteLive(root, `send ${c.intake ?? c.got?.intake ?? "?"}${c.bytes !== undefined ? ` ${(c.bytes / 1e6).toFixed(1)} MB` : ""}: ${at.join(", ")}`);
4541
+ };
4542
+ /** The reply of a send, timed: its line said at the answer — or once its writer is done, while one writes it. */
4543
+ const timedReply = (c, reply) => (code, body) => {
4544
+ c.answer = { code, at: performance.now() - c.from };
4545
+ reply(code, body);
4546
+ noteSend(c);
4547
+ };
4481
4548
  const WRITE_ANSWER_MS = Number(env.STROM_SYNC_ANSWER_MS ?? 20_000);
4482
4549
  const RETRY_MS = Number(env.STROM_SYNC_RETRY_MS ?? 30_000);
4483
4550
  const RETRIES = 5;
@@ -4496,34 +4563,67 @@ export function serveLive(root, env) {
4496
4563
  return;
4497
4564
  const next = receivedPending(root).at(-1);
4498
4565
  if (next)
4499
- write({ file: path.join(root, SYNC_INBOX, next.file), changes: next.changes, intake: next.intake }, () => { });
4566
+ write({ file: path.join(root, SYNC_INBOX, next.file), changes: next.changes, intake: next.intake, ...(next.counting ? { counting: true } : {}), clock: { from: performance.now(), intake: next.intake } }, () => { });
4500
4567
  };
4568
+ /**
4569
+ * A send written by a strom of its own. One the bridge left to it to count (`counting`: planned once, there — never
4570
+ * here as well): the app waits for the answer until that strom says how many changes it brings, from then on at most
4571
+ * WRITE_ANSWER_MS; one it refuses as it reads it is refused as the bridge refuses one (400, the file kept aside).
4572
+ */
4501
4573
  const write = (sent, reply) => {
4574
+ // its count, once known (a send counted by the bridge: known from the start)
4575
+ let count = sent.counting ? undefined : sent.changes;
4576
+ const pendingBody = (extra = {}) => ({ ok: true, inbox: false, pending: true, ...extra, ...(count !== undefined ? { changes: count } : {}), intake: sent.intake });
4502
4577
  if (writing) {
4503
- reply(202, { ok: true, inbox: false, pending: true, changes: sent.changes, intake: sent.intake });
4578
+ reply(202, pendingBody());
4504
4579
  return;
4505
4580
  }
4506
4581
  writing = sent.intake;
4582
+ const clock = sent.clock ?? { from: performance.now(), intake: sent.intake };
4583
+ clock.writing = true;
4584
+ const started = performance.now();
4507
4585
  const { command, args } = stromLauncher();
4508
4586
  const child = spawn(command, [...args, "sync", sent.file, "--apply", "--json"], {
4509
4587
  cwd: root,
4510
- env: forApp(env, root),
4588
+ env: { ...forApp(env, root), STROM_SYNC_TELL: "1" },
4511
4589
  stdio: ["ignore", "pipe", "pipe"],
4512
4590
  windowsHide: true,
4513
4591
  });
4514
4592
  track(child);
4515
4593
  let out = "";
4516
4594
  let err = "";
4517
- child.stdout.on("data", (d) => (out += d.toString("utf8")));
4518
- child.stderr.on("data", (d) => (err += d.toString("utf8")));
4595
+ let reading = false;
4519
4596
  let answered = false;
4520
- const timer = setTimeout(() => {
4521
- answered = true;
4522
- reply(202, { ok: true, inbox: false, pending: true, changes: sent.changes, intake: sent.intake });
4523
- }, WRITE_ANSWER_MS);
4597
+ let timer;
4598
+ const wait = () => {
4599
+ timer = setTimeout(() => {
4600
+ answered = true;
4601
+ reply(202, pendingBody());
4602
+ }, WRITE_ANSWER_MS);
4603
+ };
4604
+ if (count !== undefined)
4605
+ wait();
4606
+ child.stdout.on("data", (d) => (out += d.toString("utf8")));
4607
+ child.stderr.on("data", (d) => {
4608
+ err += d.toString("utf8");
4609
+ if (count !== undefined && reading)
4610
+ return;
4611
+ for (const line of err.split("\n")) {
4612
+ if (line === "strom-sync: reading")
4613
+ reading = true;
4614
+ const n = /^strom-sync: planned (\d+)$/.exec(line);
4615
+ if (n && count === undefined) {
4616
+ count = Number(n[1]);
4617
+ // counted: the app waits no longer than any send's answer waits; nothing new: answered once settled
4618
+ if (count > 0)
4619
+ wait();
4620
+ }
4621
+ }
4622
+ });
4524
4623
  child.on("error", (e) => noteLive(root, `a send could not be written: ${errorText(e)}`));
4525
4624
  child.on("close", (code) => {
4526
4625
  clearTimeout(timer);
4626
+ clock.child = performance.now() - started;
4527
4627
  let data = {};
4528
4628
  try {
4529
4629
  data = JSON.parse(out);
@@ -4531,9 +4631,60 @@ export function serveLive(root, env) {
4531
4631
  catch {
4532
4632
  // said by the exit code
4533
4633
  }
4634
+ if (data.phases)
4635
+ Object.assign(clock, { phases: data.phases, plans: data.plans, planParts: data.planParts });
4534
4636
  const why = data.message ?? err.trim().split("\n").find((l) => l.startsWith("error:"))?.slice(6).trim() ?? "the send was not written";
4535
4637
  // the research busy: tried again a while later (the app keeps following it as pending)
4536
4638
  const busy = code === EXIT.locked;
4639
+ const done = () => {
4640
+ clock.writing = false;
4641
+ noteSend(clock);
4642
+ writing = undefined;
4643
+ // the next that waits; the research busy: a while later
4644
+ if (busy) {
4645
+ clearTimeout(retryAt);
4646
+ retryAt = setTimeout(writeNext, RETRY_MS);
4647
+ retryAt.unref?.();
4648
+ }
4649
+ else
4650
+ writeNext();
4651
+ };
4652
+ if (code === 0 && count === undefined)
4653
+ count = data.changes?.length ?? 0;
4654
+ // refused as it was read, before it was counted (another research's, without the research's IDs, empty…): as the
4655
+ // bridge refuses a send it counts itself — no record of it left, the file kept aside, the app told why
4656
+ if (sent.counting && count === undefined && reading && code !== null && code !== 0 && !busy) {
4657
+ let keptAs;
4658
+ try {
4659
+ keptAs = refuseReceived(root, sent.intake);
4660
+ }
4661
+ catch (e) {
4662
+ noteLive(root, `the send ${sent.intake} refused was not kept aside: ${errorText(e)}`);
4663
+ }
4664
+ noteLive(root, `the send ${sent.intake} was refused (${data.code ?? `exit ${code}`})`);
4665
+ if (!answered) {
4666
+ let lang = "en";
4667
+ try {
4668
+ lang = Tree.open(root, env).lang;
4669
+ }
4670
+ catch {
4671
+ // said in English
4672
+ }
4673
+ const key = data.code ? REFUSED[data.code] : undefined;
4674
+ if (data.code === DISK_FULL || isDiskFull(why))
4675
+ reply(507, { ...diskFullSaid(lang, root), ...(keptAs ? { keptAs } : {}) });
4676
+ else
4677
+ reply(400, { ...(key ? said(lang, key) : { error: why, code: "tree.refused", text: why }), ...(keptAs ? { keptAs } : {}) });
4678
+ }
4679
+ return done();
4680
+ }
4681
+ // counted by its writer, nothing new: answered as a send that brings nothing (nothing waits, nothing written)
4682
+ if (sent.counting && code === 0 && count === 0) {
4683
+ noteLive(root, `the send ${sent.intake} brought nothing new${data.input ? ` (the same as ${data.input})` : ""}`);
4684
+ if (!answered)
4685
+ reply(200, { ok: true, changes: 0, file: path.basename(sent.file), inbox: false, head: head(root), conflicts: [], intake: sent.intake });
4686
+ return done();
4687
+ }
4537
4688
  if (code !== 0)
4538
4689
  noteLive(root, `the send ${sent.intake} was not written (exit ${code}${busy ? ", the research busy: tried again later" : ""}): ${why}`);
4539
4690
  // the same file as a sync before (sent again unchanged): nothing new, the input it was then only named
@@ -4559,7 +4710,7 @@ export function serveLive(root, env) {
4559
4710
  reply(200, {
4560
4711
  ok: true,
4561
4712
  inbox: false,
4562
- changes: sent.changes,
4713
+ changes: count ?? sent.changes,
4563
4714
  applied: changes.filter((c) => c.action !== "pick" && c.action !== "report").length - (data.skipped?.length ?? 0),
4564
4715
  // the people and sources it brought, under the IDs the research gave them (the app's xref → P…, S…): the app
4565
4716
  // keeps them as their REFN, its next send names them so (as an adoption's answer does)
@@ -4590,7 +4741,7 @@ export function serveLive(root, env) {
4590
4741
  });
4591
4742
  }
4592
4743
  else if (busy)
4593
- reply(202, { ok: true, inbox: false, pending: true, retry: Math.round(RETRY_MS / 1000), changes: sent.changes, intake: sent.intake });
4744
+ reply(202, pendingBody({ retry: Math.round(RETRY_MS / 1000) }));
4594
4745
  // a sentence the app shows as it is (3.8 shows "error" of a refusal), what went wrong beside it
4595
4746
  else {
4596
4747
  let lang = "en";
@@ -4622,15 +4773,7 @@ export function serveLive(root, env) {
4622
4773
  reply(500, { ...said(lang, "ui.sync.bridge.failed"), reason: why, ...(data.code ? { reasonCode: data.code } : {}), ...(data.params ? { reasonParams: data.params, reasonNames } : {}), intake: sent.intake });
4623
4774
  }
4624
4775
  }
4625
- writing = undefined;
4626
- // the next that waits; the research busy: a while later
4627
- if (busy) {
4628
- clearTimeout(retryAt);
4629
- retryAt = setTimeout(writeNext, RETRY_MS);
4630
- retryAt.unref?.();
4631
- }
4632
- else
4633
- writeNext();
4776
+ done();
4634
4777
  });
4635
4778
  };
4636
4779
  /**
@@ -4728,10 +4871,24 @@ export function serveLive(root, env) {
4728
4871
  * research, or sends one of them again (POST /sync/<R…>/again; found on Windows: sent again after an undo, nothing
4729
4872
  * new, the app and the research apart without a word).
4730
4873
  */
4731
- const take = (text, reply, again, mediaApp) => {
4874
+ const take = (text, reply, again, mediaApp, clock) => {
4875
+ const undoneFrom = performance.now();
4732
4876
  const since = undoneSince(root, text);
4877
+ if (clock)
4878
+ clock.undone = performance.now() - undoneFrom;
4733
4879
  const told = (code, body) => reply(code, since.length && code < 400 ? { ...body, undoneSince: since } : body);
4734
- const got = receiveTree(root, env, text, { ...(writing ? { keep: writing } : {}), ...(again ? { again } : {}), ...(mediaApp ? { mediaApp } : {}) });
4880
+ // written at once, nothing being written: counted by the strom that writes it, as it plans it (once, there)
4881
+ const counts = !writing && writesAtOnce();
4882
+ const times = {};
4883
+ if (clock)
4884
+ clock.got = times;
4885
+ const got = receiveTree(root, env, text, { ...(writing ? { keep: writing } : {}), ...(again ? { again } : {}), ...(mediaApp ? { mediaApp } : {}), ...(counts ? { plan: false } : {}), times });
4886
+ if (clock)
4887
+ clock.intake = got.intake;
4888
+ if (got.counting) {
4889
+ write({ ...got, ...(clock ? { clock } : {}) }, told);
4890
+ return;
4891
+ }
4735
4892
  const tree = Tree.open(root, env);
4736
4893
  // nothing new: nothing waits, nothing written
4737
4894
  if (!got.changes) {
@@ -4739,7 +4896,7 @@ export function serveLive(root, env) {
4739
4896
  return;
4740
4897
  }
4741
4898
  if (actsAsArchive(tree) || !new Settings(env, {}).syncReview(tree.config)) {
4742
- write(got, told);
4899
+ write({ ...got, ...(clock ? { clock } : {}) }, told);
4743
4900
  return;
4744
4901
  }
4745
4902
  told(200, { ok: true, changes: got.changes, file: path.basename(got.file), inbox: true, intake: got.intake });
@@ -4750,6 +4907,8 @@ export function serveLive(root, env) {
4750
4907
  if (!res.headersSent)
4751
4908
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }).end(JSON.stringify(body));
4752
4909
  };
4910
+ const clock = { from: performance.now() };
4911
+ const answer = timedReply(clock, reply);
4753
4912
  req.resume();
4754
4913
  if (!origin)
4755
4914
  return reply(403, refusal("only the Strom app may send a tree here", "app.only"));
@@ -4758,13 +4917,14 @@ export function serveLive(root, env) {
4758
4917
  return reply(404, { error: `no send ${intake.slice(0, 64)} taken back is kept here`, code: "send.none", intake });
4759
4918
  // what the app said of the send's files then (media=app) holds for it again
4760
4919
  const mediaApp = !!receivedAll(root).find((r) => r.intake === intake)?.mediaApp;
4920
+ clock.bytes = Buffer.byteLength(text);
4761
4921
  safely(req, res, () => {
4762
4922
  try {
4763
4923
  take(text, (code, body) => {
4764
4924
  if (code < 400 && typeof body.intake === "string")
4765
4925
  markSentAgain(root, intake, body.intake);
4766
- reply(code, body);
4767
- }, intake, mediaApp);
4926
+ answer(code, body);
4927
+ }, intake, mediaApp, clock);
4768
4928
  }
4769
4929
  catch (e) {
4770
4930
  const m = e.message;
@@ -4778,8 +4938,8 @@ export function serveLive(root, env) {
4778
4938
  // said in English
4779
4939
  }
4780
4940
  if (isDiskFull(e))
4781
- return reply(507, diskFullSaid(lang, root));
4782
- reply(400, key ? said(lang, key) : { error: m, code: "tree.refused", text: m });
4941
+ return answer(507, diskFullSaid(lang, root));
4942
+ answer(400, key ? said(lang, key) : { error: m, code: "tree.refused", text: m });
4783
4943
  }
4784
4944
  });
4785
4945
  };
@@ -4787,7 +4947,10 @@ export function serveLive(root, env) {
4787
4947
  const receive = (req, res, origin, as = "sync") => {
4788
4948
  // the app says the send carries every file of its tree (spec 108 P4): a place it no longer has may be taken off
4789
4949
  const mediaApp = new URLSearchParams((req.url ?? "").split("?")[1] ?? "").get("media") === "app";
4790
- const reply = (code, body) => res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }).end(JSON.stringify(body));
4950
+ const clock = { from: performance.now() };
4951
+ const answer = (code, body) => res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }).end(JSON.stringify(body));
4952
+ // a tree's send timed (live.log); an adoption, a refusal before the tree came: answered as they are
4953
+ const reply = as === "sync" ? timedReply(clock, answer) : answer;
4791
4954
  const lang = () => {
4792
4955
  try {
4793
4956
  return Tree.open(root, env).lang;
@@ -4812,6 +4975,8 @@ export function serveLive(root, env) {
4812
4975
  });
4813
4976
  req.on("error", (e) => noteLive(root, `a tree from the app did not come whole: ${errorText(e)}`));
4814
4977
  req.on("end", () => safely(req, res, () => {
4978
+ clock.body = performance.now() - clock.from;
4979
+ clock.bytes = size;
4815
4980
  if (over) {
4816
4981
  reply(413, said(lang(), "ui.sync.bridge.large"));
4817
4982
  return;
@@ -4819,8 +4984,20 @@ export function serveLive(root, env) {
4819
4984
  try {
4820
4985
  // the version the app says with it (its file writes none of its own): the tree is read as that app means it
4821
4986
  // a GEDCOM's bytes by the same rule as a file's (the app sends UTF-8: the same text), the app's JSON as UTF-8
4987
+ const decodeFrom = performance.now();
4822
4988
  const body = Buffer.concat(chunks);
4823
4989
  const text = stampAppVersion(looksLikeGedcom(body) ? decodeGedcom(body).text : body.toString("utf8"), saidAppVersion(req));
4990
+ clock.decode = performance.now() - decodeFrom;
4991
+ if (as === "sync") {
4992
+ // files by reference (spec 133): one the research cannot find refuses the whole send — nothing kept, no record
4993
+ const { unknown, ...counts } = checkMediaRefs(text, { tree: () => readTree(root, env), store: new Settings(env, {}).shared()?.value });
4994
+ clock.media = counts;
4995
+ if (unknown.length) {
4996
+ noteLive(root, `send refused: ${MEDIA_REF_UNKNOWN} (${unknown.length} ${unknown.length === 1 ? "file" : "files"} by reference not here)`);
4997
+ reply(409, { ok: false, code: MEDIA_REF_UNKNOWN, error: `the research does not have ${unknown.length === 1 ? "a file" : `${unknown.length} files`} the tree names by reference — send it with the files' data`, shas: unknown });
4998
+ return;
4999
+ }
5000
+ }
4824
5001
  if (as === "adopt") {
4825
5002
  if (adopting) {
4826
5003
  reply(409, said(lang(), "ui.sync.bridge.adopting"));
@@ -4829,7 +5006,7 @@ export function serveLive(root, env) {
4829
5006
  adopt(receiveAdopted(root, text, origin), reply, lang(), appVersionOf(req, new Settings(env, {})));
4830
5007
  return;
4831
5008
  }
4832
- take(text, reply, undefined, mediaApp);
5009
+ take(text, reply, undefined, mediaApp, clock);
4833
5010
  }
4834
5011
  catch (e) {
4835
5012
  const m = e.message;
@@ -4878,6 +5055,7 @@ export function serveLive(root, env) {
4878
5055
  let named;
4879
5056
  let note;
4880
5057
  let meta;
5058
+ let list;
4881
5059
  let region;
4882
5060
  let batch;
4883
5061
  let where;
@@ -4949,13 +5127,23 @@ export function serveLive(root, env) {
4949
5127
  read = toRead === "1";
4950
5128
  if (families.length && (source || task || batch))
4951
5129
  throw new Error("X-Strom-Family: a couple's original comes in no batch, for no task and is no image of a source");
5130
+ at = "X-Strom-List-Ref";
5131
+ // the list of people it is sent to (spec 137, media.list): one the app put first (PUT lists/<id>)
5132
+ list = header("x-strom-list-ref")?.trim() || undefined;
5133
+ if (list !== undefined && !LIST_ID.test(list))
5134
+ throw new Error("X-Strom-List-Ref: the list's mark (PUT lists/<id>)");
5135
+ // (with X-Strom-Source: a scan of a source of the list's people — media.list.source)
5136
+ if (list && (task || batch || read))
5137
+ throw new Error("X-Strom-List-Ref: a file sent to a list comes in no batch, for no task and not to read");
5138
+ if (list && !readSentList(root, list))
5139
+ throw new StromError(`no list ${list} sent here — send the list (PUT lists/${list}) and the file again`, { code: "media.no-list", params: { list } });
4952
5140
  meta = checkOriginalMeta(tree, { persons, source, families });
4953
5141
  }
4954
5142
  catch (e) {
4955
5143
  // a person or a source the research has not got: 404, its JSON body telling it from an address that is no bridge's
4956
5144
  const m = e.message;
4957
5145
  const coded = e instanceof StromError && e.code ? refusal(m, e.code, e.params ?? {}) : refusal(m, "media.bad-header", { header: at });
4958
- return refuse(/^no (person|source|family)/.test(m) ? 404 : 400, coded);
5146
+ return refuse(/^no (person|source|family|list)/.test(m) ? 404 : 400, coded);
4959
5147
  }
4960
5148
  // a file for a task (its "Add a file"): only for a task that waits for one — else refused before anything is kept
4961
5149
  // (the app offers the inbox folder then)
@@ -4972,7 +5160,52 @@ export function serveLive(root, env) {
4972
5160
  // whose answer says what became of it
4973
5161
  const later = /(?:^|[,;\s])respond-async(?:$|[,;\s])/i.test(header("prefer") ?? "") && !forTask && !read && !meta.source && !region;
4974
5162
  const app = header("x-strom-app-version");
4975
- receiveOriginal(receiver, req, res, { sha, name, note, persons: meta.persons, ...(meta.families ? { families: meta.families } : {}), source: meta.source, region, batch, where, zip, task: forTask, ...(image !== undefined ? { image } : {}), ...(replace ? { replace } : {}), ...(read ? { read } : {}), ...(later ? { async: { origin, ...(app ? { app } : {}) } } : {}) });
5163
+ receiveOriginal(receiver, req, res, { sha, name, note, persons: meta.persons, ...(meta.families ? { families: meta.families } : {}), ...(list ? { list } : {}), source: meta.source, region, batch, where, zip, task: forTask, ...(image !== undefined ? { image } : {}), ...(replace ? { replace } : {}), ...(read ? { read } : {}), ...(later ? { async: { origin, ...(app ? { app } : {}) } } : {}) });
5164
+ };
5165
+ /**
5166
+ * A list of people the app sends material to (PUT lists/<id>, spec 137, feature media.list): checked and kept by the
5167
+ * bridge (.strom/lists/<id>.json) until a file names it (X-Strom-List-Ref) — the strom that takes the file writes it
5168
+ * into the research. {list, persons, unknown}: how many of its people, how many of them the research has not got.
5169
+ */
5170
+ const listPut = (req, res, origin, id) => {
5171
+ const json = (code, body) => {
5172
+ if (!res.headersSent)
5173
+ res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }).end(JSON.stringify(body));
5174
+ };
5175
+ if (!origin) {
5176
+ req.resume();
5177
+ return json(403, refusal("only the Strom app may send a list here", "app.only"));
5178
+ }
5179
+ const chunks = [];
5180
+ let size = 0;
5181
+ let over = false;
5182
+ req.on("data", (c) => {
5183
+ if (over)
5184
+ return;
5185
+ size += c.length;
5186
+ if (size > LIST_BODY_MAX)
5187
+ over = true;
5188
+ else
5189
+ chunks.push(c);
5190
+ });
5191
+ req.on("end", () => safely(req, res, () => {
5192
+ if (over)
5193
+ return json(413, refusal(`a list's body is at most ${LIST_BODY_MAX} bytes`, "list.large", { max: String(LIST_BODY_MAX) }));
5194
+ let body;
5195
+ try {
5196
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
5197
+ }
5198
+ catch {
5199
+ body = undefined;
5200
+ }
5201
+ const l = checkSentList(id, body);
5202
+ if ("code" in l)
5203
+ return json(l.code === "list.large" ? 413 : 400, refusal(l.why, l.code));
5204
+ keepSentList(root, l);
5205
+ const tree = readTree(root, env);
5206
+ const unknown = l.persons.filter((p) => tree.get(p)?.type !== "person").length;
5207
+ json(200, { list: l.id, persons: l.persons.length, unknown });
5208
+ }));
4976
5209
  };
4977
5210
  // closed one at a time with the queue's writes: the batch's queued files and its close one commit
4978
5211
  const closeBatchNow = (id, extra, reply) => media.close(id, (done) => closeBatchBy(receiver, id, extra, (code, body) => {
@@ -5023,7 +5256,8 @@ export function serveLive(root, env) {
5023
5256
  const sha = raw.toLowerCase();
5024
5257
  if (sha in known)
5025
5258
  continue;
5026
- const k = knownOriginal(tree, shared, sha) ?? workingCopyOf(tree, shared, sha);
5259
+ // a working copy by its own hash too (spec 133: the app names the bytes it would send by reference)
5260
+ const k = knownOriginal(tree, shared, sha) ?? workingCopyOf(tree, shared, sha) ?? workingCopyBySha(tree, shared, sha);
5027
5261
  known[sha] = k ? { id: k.id, kind: k.kind, mime: k.mime, bytes: k.bytes, here: !!k.file && fs.existsSync(k.file) } : queued.has(sha) ? { queued: true } : null;
5028
5262
  }
5029
5263
  json(200, { known });
@@ -184,6 +184,34 @@ function readSite(stateDir, site) {
184
184
  export function sitePagesHere(stateDir, site, windowMs, now = Date.now()) {
185
185
  return readSite(stateDir, site).requests.filter((r) => r.at > now - windowMs && r.at <= now + windowMs).length;
186
186
  }
187
+ /**
188
+ * When the site takes a page of the agents' web tools again on this computer: the moment fewer than `limit − free + 1`
189
+ * of its pages lie within `windowMs` — the oldest that must leave the window, plus the window (page by page: one more
190
+ * used, the next frees as the one after it leaves). `free`: how many pages must be free (1: the next page). `now` when
191
+ * that many are free already.
192
+ */
193
+ export function siteFreeAt(stateDir, site, windowMs, limit, now = Date.now(), free = 1) {
194
+ const ats = readSite(stateDir, site)
195
+ .requests.map((r) => r.at)
196
+ .filter((at) => at > now - windowMs && at <= now + windowMs)
197
+ .sort((a, b) => a - b);
198
+ const leave = ats.length - (limit - Math.max(1, Math.min(free, limit)));
199
+ if (leave <= 0)
200
+ return now;
201
+ return ats[leave - 1] + windowMs;
202
+ }
203
+ /** The sites whose pages the agents' web tools had on this computer (their files in the limiter's folder). */
204
+ export function webSites(stateDir) {
205
+ try {
206
+ return fs
207
+ .readdirSync(stateDir)
208
+ .filter((f) => f.startsWith("site~") && f.endsWith(".web.json"))
209
+ .map((f) => f.slice(5, -9));
210
+ }
211
+ catch {
212
+ return [];
213
+ }
214
+ }
187
215
  /** One page of a site more, of the session `who` (under the site's lock where the caller has it). Never throws. */
188
216
  export function noteSitePage(stateDir, site, who, now = Date.now()) {
189
217
  try {