strom-research 1.35.0 → 1.36.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 (59) hide show
  1. package/CHANGELOG.cs.md +45 -0
  2. package/CHANGELOG.de.md +53 -0
  3. package/CHANGELOG.md +48 -0
  4. package/CHANGELOG.pl.md +47 -0
  5. package/assets/lang/cs.json +47 -5
  6. package/assets/lang/de.json +47 -5
  7. package/assets/lang/pl.json +46 -4
  8. package/assets/plugins/gates/claude-usage/gate.ts +94 -16
  9. package/dist/cli/help.js +2 -2
  10. package/dist/cli/menu-links.js +58 -11
  11. package/dist/cli/menu-settings.js +19 -0
  12. package/dist/cli/menu-waiting.js +50 -1
  13. package/dist/cli/ui.js +41 -5
  14. package/dist/commands/analysis.js +20 -1
  15. package/dist/commands/guide.js +4 -1
  16. package/dist/commands/index.js +1 -0
  17. package/dist/commands/intake.js +32 -9
  18. package/dist/commands/links.js +10 -6
  19. package/dist/commands/media.js +166 -32
  20. package/dist/commands/setup.js +6 -0
  21. package/dist/commands/sourceretract.js +139 -0
  22. package/dist/commands/sources.js +42 -13
  23. package/dist/commands/sync.js +5 -3
  24. package/dist/commands/tasks.js +37 -9
  25. package/dist/commands/verify.js +7 -4
  26. package/dist/core/actions.js +11 -9
  27. package/dist/core/busy.js +9 -0
  28. package/dist/core/changelog.js +17 -0
  29. package/dist/core/config.js +7 -0
  30. package/dist/core/evidence.js +16 -0
  31. package/dist/core/import.js +9 -3
  32. package/dist/core/inboxwait.js +133 -15
  33. package/dist/core/inboxwatch.js +5 -4
  34. package/dist/core/links.js +13 -2
  35. package/dist/core/live.js +368 -33
  36. package/dist/core/material.js +12 -5
  37. package/dist/core/materialdelete.js +97 -23
  38. package/dist/core/media.js +4 -0
  39. package/dist/core/origin.js +16 -6
  40. package/dist/core/phrases.js +6 -0
  41. package/dist/core/queue.js +12 -4
  42. package/dist/core/report.js +1 -1
  43. package/dist/core/samescan.js +359 -0
  44. package/dist/core/sort.js +1 -1
  45. package/dist/core/sourcefields.js +16 -0
  46. package/dist/core/sourceretract.js +531 -0
  47. package/dist/core/sync.js +152 -7
  48. package/dist/core/taskaudit.js +104 -6
  49. package/dist/core/taskkind.js +58 -0
  50. package/dist/core/tree.js +1 -1
  51. package/dist/core/verify.js +12 -6
  52. package/dist/core/verifyfacts.js +7 -0
  53. package/dist/core/waiting.js +22 -3
  54. package/dist/core/waitkept.js +2 -0
  55. package/dist/gedcom/export.js +32 -9
  56. package/dist/gedcom/validate.js +8 -3
  57. package/dist/image/index.js +6 -3
  58. package/dist/image/jpeg-decode.js +80 -21
  59. package/package.json +4 -1
@@ -0,0 +1,531 @@
1
+ // A source deleted by the person (spec 117, K1.1–K1.7): in the research it is retracted — reversibly, with its history.
2
+ // Its citations are taken off the facts, names and families (the values stay, a status the citations left cannot carry
3
+ // is lowered) and kept in the source (Source.deleted), so that strom source restore puts back exactly what was there;
4
+ // a task working on it alone is given up, one with other places narrowed; a conflict standing on it is marked for review
5
+ // (its state stays). The text of a story never changes. One write, one operation of the history (source.retract /
6
+ // source.restore); the person's alone: strom source retract (consent or the bridge's confirm), never an agent's.
7
+ import { UsageError } from "./errors.js";
8
+ import { checkStatus } from "./evidence.js";
9
+ import { canonicalize } from "./json.js";
10
+ import { settledClaim } from "./labels.js";
11
+ import { phrase } from "./phrases.js";
12
+ import { sha256, signRecord, verifyRecord } from "./seal.js";
13
+ import { sourcesNamed, storySources } from "./storykeep.js";
14
+ import { now } from "./tree.js";
15
+ /** The bridge's feature of deleting a source (/status.features): retract, restore, conflict/keep, the marks of review. */
16
+ export const SOURCE_RETRACT_FEATURE = "source.retract";
17
+ /** The reason of a source deleted by the person (Source.retracted.reason). */
18
+ export const DELETED = "deleted";
19
+ /** How many sources one call takes. */
20
+ export const RETRACT_MOST = 50;
21
+ /** How many items a list of the impacts holds; the rest only counted (more). */
22
+ export const IMPACTS_MAX = 200;
23
+ /** How long the bridge's confirmation of a dry run holds. */
24
+ export const RETRACT_CONFIRM_MS = 15 * 60_000;
25
+ /** The mark of review of a conflict a deleted source stood on (2 _STROM_REVIEW). */
26
+ export const REVIEW_RETRACTED = "source.retracted";
27
+ const ACTIVE = new Set(["open", "doing", "parked", "waiting"]);
28
+ /** A source deleted by the person (strom source retract): retracted, and its citations kept to be put back. */
29
+ export function deletedSource(s) {
30
+ return !!s && s.type === "source" && s.retracted?.reason === DELETED && !!s.deleted;
31
+ }
32
+ /** The sources asked: each the research's (source.unknown), at most RETRACT_MOST (source.body). */
33
+ function sourcesAsked(tree, ids) {
34
+ const norm = [...new Set(ids.map((x) => x.trim().toUpperCase()).filter(Boolean))].map((x) => (/^S\d+$/u.test(x) ? `S${x.slice(1).padStart(4, "0")}` : x));
35
+ if (!norm.length || norm.length > RETRACT_MOST)
36
+ throw new UsageError(`sources: 1 to ${RETRACT_MOST} IDs (S…)`, { code: "source.body" });
37
+ return norm.map((id) => {
38
+ const s = tree.get(id);
39
+ if (!s || s.type !== "source")
40
+ throw new UsageError(`no source ${id} in the research`, { hint: "strom source list", code: "source.unknown", params: { id } });
41
+ return s;
42
+ });
43
+ }
44
+ const live = (r) => !r.retracted && !r.mergedInto;
45
+ /** The sources a citation list keeps that /tree.ged gives (not taken back), apart from those going. */
46
+ function othersIn(tree, list, going) {
47
+ return new Set(list.map((c) => c.source).filter((s) => !going.has(s) && liveSource(tree, s))).size;
48
+ }
49
+ function liveSource(tree, id) {
50
+ const s = tree.get(id);
51
+ return !!s && s.type === "source" && !s.retracted;
52
+ }
53
+ /** The highest status the citations left carry: the status as it is, else probable, else a lead (as sync's fact.uncite). */
54
+ export function carriedStatus(tree, status, citations) {
55
+ for (const s of [status, "probable", "lead"]) {
56
+ try {
57
+ checkStatus(tree, s, citations);
58
+ return s;
59
+ }
60
+ catch {
61
+ // less sure
62
+ }
63
+ }
64
+ return "lead";
65
+ }
66
+ /** The story's versions (the approved one and the one waiting beside it). */
67
+ const versions = (st) => (st ? [st, ...(st.draft ? [st.draft] : [])] : []);
68
+ /** A conflict stands on the source: a value of it, the citations of the user's edit or of a proposal, its decision. */
69
+ function standsOn(tree, c, id) {
70
+ if (c.claims.some((cl) => settledClaim(tree, c, cl).source === id))
71
+ return true;
72
+ if (c.edit?.cites?.some((x) => x.source === id) || c.proposal?.cites?.some((x) => x.source === id))
73
+ return true;
74
+ return sourcesNamed(tree, `${c.resolution ?? ""}\n${c.reasoning ?? ""}`).includes(id);
75
+ }
76
+ /** The open session holding a task (its agent at work on it). */
77
+ function holderOf(tree, task) {
78
+ return tree.list("session").find((s) => s.task === task && s.state === "open")?.id;
79
+ }
80
+ /**
81
+ * What deleting the sources would do, worked out on copies: the impacts of each (as if alone: its own counts) and the
82
+ * records as they would be written with all of them gone.
83
+ */
84
+ function plan(tree, sources, at, how = {}) {
85
+ const changed = new Map();
86
+ const edit = (r) => {
87
+ let got = changed.get(r.id);
88
+ if (!got)
89
+ changed.set(r.id, (got = structuredClone(r)));
90
+ return got;
91
+ };
92
+ const deletions = new Map();
93
+ const impacts = [];
94
+ const persons = tree.list("person").filter(live);
95
+ const families = tree.list("family").filter(live);
96
+ const reason = how.reason?.trim().normalize("NFC");
97
+ for (const s of sources) {
98
+ const id = s.id;
99
+ const alone = new Set([id]);
100
+ const cites = [];
101
+ const bare = [];
102
+ const lowered = [];
103
+ const counts = { persons: 0, names: 0, events: 0, families: 0, stories: 0 };
104
+ const kept = [];
105
+ const statuses = [];
106
+ const owners = new Set();
107
+ // one list of citations (a name's, a fact's, a family's own): its lines of the source counted, taken off the copy
108
+ const take = (owner, fact, list, where) => {
109
+ const all = list ?? [];
110
+ if (!all.some((c) => c.source === id))
111
+ return undefined;
112
+ owners.add(owner);
113
+ const others = othersIn(tree, all, alone);
114
+ all.forEach((c, i) => {
115
+ if (c.source !== id)
116
+ return;
117
+ cites.push({ owner, fact, ...(where.event ? { event: where.event } : {}), others, ...(c.locator ? { locator: c.locator } : {}), ...(c.main ? { main: true } : {}) });
118
+ kept.push({ owner, fact, ...(where.event ? { event: where.event } : {}), ...(where.name ? { name: where.name } : {}), at: i, citation: c });
119
+ });
120
+ if (fact !== "FAM" && !others)
121
+ bare.push({ owner, fact, ...(where.event ? { event: where.event } : {}) });
122
+ return all.filter((c) => c.source !== id);
123
+ };
124
+ const facts = (owner, events, copy) => {
125
+ events.forEach((e, i) => {
126
+ if (e.retracted)
127
+ return;
128
+ const rest = take(owner, e.kind, e.citations, { event: e.id });
129
+ if (!rest)
130
+ return;
131
+ if (owner.startsWith("F"))
132
+ counts.families += e.citations.length - rest.length;
133
+ else
134
+ counts.events += e.citations.length - rest.length;
135
+ // as sure as the citations left (of the sources that stay) carry it — with all the sources asked gone
136
+ const target = copy()[i];
137
+ const after = target.citations.filter((c) => c.source !== id);
138
+ const to = carriedStatus(tree, target.status, after);
139
+ const by = carriedStatus(tree, e.status, rest);
140
+ if (by !== e.status)
141
+ lowered.push({ owner, fact: e.kind, event: e.id, from: e.status, to: by });
142
+ if (to !== target.status)
143
+ statuses.push({ owner, event: e.id, from: target.status, to });
144
+ target.citations = after;
145
+ target.status = to;
146
+ });
147
+ };
148
+ for (const p of persons) {
149
+ p.names.forEach((n, i) => {
150
+ const rest = take(p.id, "NAME", n.citations, { name: { index: i, given: n.given, surname: n.surname } });
151
+ if (!rest)
152
+ return;
153
+ counts.names += (n.citations ?? []).length - rest.length;
154
+ const name = edit(p).names[i];
155
+ const after = (name.citations ?? []).filter((c) => c.source !== id);
156
+ if (after.length)
157
+ name.citations = after;
158
+ else
159
+ delete name.citations;
160
+ });
161
+ facts(p.id, p.events, () => edit(p).events);
162
+ }
163
+ for (const f of families) {
164
+ const rest = take(f.id, "FAM", f.citations, {});
165
+ if (rest) {
166
+ counts.families += (f.citations ?? []).length - rest.length;
167
+ const copy = edit(f);
168
+ const after = (copy.citations ?? []).filter((c) => c.source !== id);
169
+ if (after.length)
170
+ copy.citations = after;
171
+ else
172
+ delete copy.citations;
173
+ }
174
+ facts(f.id, f.events, () => edit(f).events);
175
+ }
176
+ // the stories it is a source of (2 SOUR: through their facts, their background, their text): the text never changes
177
+ const stories = [];
178
+ for (const r of [...persons, ...families]) {
179
+ const vs = versions(r.story);
180
+ if (!vs.some((v) => storySources(tree, v).some((x) => x.id === id)))
181
+ continue;
182
+ stories.push({ owner: r.id, inText: vs.some((v) => sourcesNamed(tree, [v.title, v.text, v.note].filter(Boolean).join("\n")).includes(id)) });
183
+ }
184
+ counts.stories = stories.length;
185
+ // the conflicts it is a source of: marked for review whatever their state; those of the same people stay
186
+ const conflicts = [];
187
+ const marked = [];
188
+ for (const c of tree.list("conflict")) {
189
+ if (c.retracted)
190
+ continue;
191
+ if (standsOn(tree, c, id)) {
192
+ conflicts.push({ id: c.id, status: c.state, becomes: "review" });
193
+ marked.push(c.id);
194
+ const copy = edit(c);
195
+ copy.review = { why: REVIEW_RETRACTED, sources: [...new Set([...(copy.review?.sources ?? []), id])], at };
196
+ }
197
+ else if (c.subject.some((x) => owners.has(x)))
198
+ conflicts.push({ id: c.id, status: c.state, becomes: "unchanged" });
199
+ }
200
+ // the tasks of it not ended: given up when it was their only place, else without it (one of a wording proposed to
201
+ // the person stays: the proposal stays with the source)
202
+ const tasks = [];
203
+ const taskWas = [];
204
+ for (const t0 of tree.list("task")) {
205
+ if (t0.retracted || !ACTIVE.has(t0.state) || t0.proposal)
206
+ continue;
207
+ const t = changed.get(t0.id) ?? t0;
208
+ if (!t.where.includes(id) && !t.subject.includes(id))
209
+ continue;
210
+ const where = t.where.filter((w) => w !== id);
211
+ const held = t.state === "doing" ? holderOf(tree, t.id) : undefined;
212
+ const copy = edit(t0);
213
+ taskWas.push({ was: structuredClone(t), after: at });
214
+ if (!where.length) {
215
+ tasks.push({ id: t.id, state: t.state, becomes: "dropped", ...(held ? { heldBy: held } : {}) });
216
+ copy.state = "dropped";
217
+ copy.result = phrase(tree.lang, "source.retracted.task", { id });
218
+ for (const k of ["parkedFor", "parkedUntil", "parkedReason", "awaitsPermission", "waitingOn", "awaits", "awaitsCheck", "wait", "sent", "heldBy", "heldFrom"])
219
+ delete copy[k];
220
+ }
221
+ else {
222
+ tasks.push({ id: t.id, state: t.state, becomes: "narrowed", ...(held ? { heldBy: held } : {}) });
223
+ copy.where = where;
224
+ copy.subject = copy.subject.filter((x) => x !== id);
225
+ }
226
+ }
227
+ // its files of the material (they stay there), its images from an archive (they stay with it)
228
+ const images = new Set([...(s.media ?? []), ...(s.clips ?? []).map((c) => c.media)].filter((m) => m.startsWith("M")));
229
+ const shas = new Set([...images].map((m) => tree.get(m)?.sha).filter(Boolean));
230
+ const files = tree
231
+ .list("input")
232
+ .filter((i) => !i.retracted && (i.id === s.input || i.source === id || i.sorted?.source === id || (s.clips ?? []).some((c) => c.media === i.id) || (!!i.sha && shas.has(i.sha)) || (!!i.working?.sha && shas.has(i.working.sha))))
233
+ .map((i) => i.id);
234
+ const cap = (list) => list.slice(0, IMPACTS_MAX);
235
+ const over = (list) => Math.max(0, list.length - IMPACTS_MAX);
236
+ impacts.push({
237
+ id,
238
+ title: s.title,
239
+ ...(s.input ? { input: s.input } : {}),
240
+ counts,
241
+ cites: cap(cites),
242
+ stories: cap(stories),
243
+ bare: cap(bare),
244
+ lowered: cap(lowered),
245
+ conflicts: cap(conflicts),
246
+ tasks: cap(tasks),
247
+ files: cap(files),
248
+ images: images.size,
249
+ more: { cites: over(cites), stories: over(stories), bare: over(bare), lowered: over(lowered), conflicts: over(conflicts), tasks: over(tasks), files: over(files) },
250
+ });
251
+ deletions.set(id, {
252
+ at,
253
+ by: "user",
254
+ ...(how.via ? { via: how.via } : {}),
255
+ ...(reason ? { reason } : {}),
256
+ cites: kept,
257
+ ...(statuses.length ? { lowered: statuses } : {}),
258
+ ...(taskWas.length ? { tasks: taskWas } : {}),
259
+ ...(marked.length ? { conflicts: marked } : {}),
260
+ });
261
+ }
262
+ return { impacts, changed, deletions };
263
+ }
264
+ /** A source already retracted, refused (409 source.retracted). */
265
+ function refuseRetracted(s) {
266
+ if (s.retracted)
267
+ throw new UsageError(`${s.id} is retracted already${s.retracted.reason === DELETED ? " (deleted by the person)" : ""}`, {
268
+ hint: deletedSource(s) ? `strom source restore ${s.id} puts it back` : "nothing to delete",
269
+ code: "source.retracted",
270
+ params: { id: s.id },
271
+ });
272
+ }
273
+ /** What deleting the sources would take with it (strom source retract --dry-run, the bridge's dryRun): nothing written. */
274
+ export function retractImpacts(tree, ids) {
275
+ const sources = sourcesAsked(tree, ids);
276
+ for (const s of sources)
277
+ refuseRetracted(s);
278
+ return plan(tree, sources, now()).impacts;
279
+ }
280
+ /**
281
+ * The sources deleted by the person: retracted (reason "deleted"), their citations taken off and kept in each
282
+ * (Source.deleted), statuses lowered to what is left, tasks given up or narrowed, conflicts marked — one operation
283
+ * source.retract. All or nothing: a source unknown or retracted, and nothing is written. Holds the tree lock; the caller
284
+ * commits (a command of strom).
285
+ */
286
+ export function retractSources(tree, ids, how = {}) {
287
+ return tree.withTreeLock(() => {
288
+ const sources = sourcesAsked(tree, ids);
289
+ for (const s of sources)
290
+ refuseRetracted(s);
291
+ const at = now();
292
+ const { impacts, changed, deletions } = plan(tree, sources, at, how);
293
+ const records = [...changed.values()].map((r) => ({ ...r, updated: at }));
294
+ for (const s of sources)
295
+ records.push({ ...s, retracted: { at, reason: DELETED }, deleted: deletions.get(s.id), updated: at });
296
+ const cites = impacts.reduce((n, i) => n + i.counts.names + i.counts.events + i.counts.families, 0);
297
+ const stories = impacts.reduce((n, i) => n + i.counts.stories, 0);
298
+ const tasks = impacts.reduce((n, i) => n + i.tasks.length + i.more.tasks, 0);
299
+ const conflicts = impacts.reduce((n, i) => n + i.conflicts.filter((c) => c.becomes === "review").length, 0);
300
+ const reason = how.reason?.trim().normalize("NFC");
301
+ tree.putMany(records, [], {
302
+ op: "source.retract",
303
+ targets: [...sources.map((s) => s.id), ...changed.keys()],
304
+ summary: `${sources.map((s) => s.id).join(", ")} deleted by the user${how.via === "bridge" ? " in the Strom app" : how.via === "terminal" ? " in the terminal" : ""}: ${cites} citation(s), ${stories} story(ies), ${tasks} task(s), ${conflicts} conflict(s)`,
305
+ ...(reason ? { reason } : {}),
306
+ });
307
+ return { sources: sources.map((s) => s.id), retracted: sources.map((s) => s.id), impacts };
308
+ });
309
+ }
310
+ /** The record a merged one went into, and on (undefined: none, or no longer there). */
311
+ function liveOwner(tree, id, get) {
312
+ let r = get(id);
313
+ for (let i = 0; r && r.mergedInto && i < 20; i++)
314
+ r = get(r.mergedInto);
315
+ return r && live(r) ? r : undefined;
316
+ }
317
+ /**
318
+ * The sources asked, each one the person deleted (the bridge checks them before it runs strom source restore). Refused:
319
+ * none or more than RETRACT_MOST (source.body), unknown (source.unknown), not retracted (source.notRetracted), retracted
320
+ * otherwise than deleted (source.notRestorable, why merged | other).
321
+ */
322
+ export function restorable(tree, ids) {
323
+ const sources = sourcesAsked(tree, ids);
324
+ for (const s of sources) {
325
+ if (!s.retracted)
326
+ throw new UsageError(`${s.id} is not retracted`, { code: "source.notRetracted", params: { id: s.id } });
327
+ if (!deletedSource(s))
328
+ throw new UsageError(`${s.id} was retracted otherwise than deleted by the person (${s.mergedInto ? `merged into ${s.mergedInto}` : s.retracted.reason}): restoring does not bring it back`, {
329
+ code: "source.notRestorable",
330
+ params: { id: s.id, why: s.mergedInto ? "merged" : "other" },
331
+ });
332
+ }
333
+ return sources;
334
+ }
335
+ /**
336
+ * The deleted sources put back (strom source restore): the same IDs, each citation kept on the fact it was on — found
337
+ * by its ID wherever it is now (a person merged since: under the one it went into) — unless gone (the fact taken back)
338
+ * or there already; the main citation only where no other became main meanwhile; a status the deletion lowered only
339
+ * where nobody changed it since and the citations carry it; the tasks it changed where unchanged since; the marks of
340
+ * review gone. One operation source.restore. Refused: a source not retracted (source.notRetracted), one retracted
341
+ * otherwise (source.notRestorable, why merged | other). Holds the tree lock; the caller commits.
342
+ */
343
+ export function restoreSources(tree, ids) {
344
+ return tree.withTreeLock(() => {
345
+ const sources = restorable(tree, ids);
346
+ const asked = new Set(sources.map((s) => s.id));
347
+ const at = now();
348
+ const changed = new Map();
349
+ const edit = (r) => {
350
+ let got = changed.get(r.id);
351
+ if (!got)
352
+ changed.set(r.id, (got = structuredClone(r)));
353
+ return got;
354
+ };
355
+ const current = (id) => changed.get(id) ?? tree.get(id);
356
+ // where each fact is now: by its ID (a merge moves facts with their IDs)
357
+ const owners = new Map();
358
+ for (const t of ["person", "family"])
359
+ for (const r of tree.list(t))
360
+ if (live(r))
361
+ for (const e of r.events)
362
+ owners.set(e.id, r.id);
363
+ const out = { restored: [], citations: 0, skipped: [], raised: 0, tasks: [], conflicts: [] };
364
+ const records = [];
365
+ for (const s of sources) {
366
+ const d = s.deleted;
367
+ const skip = (c, fact, why) => out.skipped.push({ source: s.id, owner: c.owner, fact, ...(c.event ? { event: c.event } : {}), why });
368
+ // the place it goes back into a list: where it was, the main citation first
369
+ const put = (list, c, fact) => {
370
+ const all = list ?? [];
371
+ if (all.some((x) => x.source === c.citation.source && (x.locator ?? "") === (c.citation.locator ?? ""))) {
372
+ skip(c, fact, "already");
373
+ return undefined;
374
+ }
375
+ let cite = c.citation;
376
+ if (cite.main && all.some((x) => x.main)) {
377
+ const { main: _main, ...plain } = cite;
378
+ cite = plain;
379
+ skip(c, fact, "main");
380
+ }
381
+ const i = cite.main ? 0 : Math.min(c.at, all.length);
382
+ out.citations++;
383
+ return [...all.slice(0, i), cite, ...all.slice(i)];
384
+ };
385
+ for (const c of d.cites) {
386
+ if (c.event) {
387
+ const ownerId = owners.get(c.event);
388
+ const owner = ownerId ? current(ownerId) : undefined;
389
+ const e = owner?.events.find((x) => x.id === c.event);
390
+ if (!owner || !e || e.retracted) {
391
+ skip(c, c.fact, "gone");
392
+ continue;
393
+ }
394
+ const next = put(e.citations, c, e.kind);
395
+ if (next)
396
+ edit(owner).events.find((x) => x.id === c.event).citations = next;
397
+ continue;
398
+ }
399
+ if (c.name) {
400
+ const p = liveOwner(tree, c.owner, (id) => current(id));
401
+ const n = c.name;
402
+ const same = (x) => x.given === n.given && x.surname === n.surname;
403
+ const i = p ? (p.names[n.index] && same(p.names[n.index]) ? n.index : p.names.findIndex(same)) : -1;
404
+ if (!p || i < 0) {
405
+ skip(c, "NAME", "gone");
406
+ continue;
407
+ }
408
+ const next = put(p.names[i].citations, c, "NAME");
409
+ if (next)
410
+ edit(p).names[i].citations = next;
411
+ continue;
412
+ }
413
+ const f = liveOwner(tree, c.owner, (id) => current(id));
414
+ if (!f) {
415
+ skip(c, "FAM", "gone");
416
+ continue;
417
+ }
418
+ const next = put(f.citations, c, "FAM");
419
+ if (next)
420
+ edit(f).citations = next;
421
+ }
422
+ // the statuses it lowered: back where nobody changed them since and the citations carry them
423
+ for (const l of d.lowered ?? []) {
424
+ const ownerId = owners.get(l.event);
425
+ const owner = ownerId ? current(ownerId) : undefined;
426
+ const e = owner?.events.find((x) => x.id === l.event);
427
+ if (!owner || !e || e.retracted || e.status !== l.to || carriedStatus(tree, l.from, e.citations) !== l.from)
428
+ continue;
429
+ edit(owner).events.find((x) => x.id === l.event).status = l.from;
430
+ out.raised++;
431
+ }
432
+ // the tasks it changed, as they were — where nothing changed them since; never with a place another source still
433
+ // deleted was (deleted with it, not restored now): a task left with no place stays given up
434
+ for (const t of d.tasks ?? []) {
435
+ const cur = current(t.was.id);
436
+ if (!cur || cur.updated !== t.after)
437
+ continue;
438
+ const was = structuredClone(t.was);
439
+ const gone = (x) => !asked.has(x) && deletedSource(tree.get(x));
440
+ if (was.where.some(gone) || was.subject.some(gone)) {
441
+ was.where = was.where.filter((x) => !gone(x));
442
+ was.subject = was.subject.filter((x) => !gone(x));
443
+ if (!was.where.length)
444
+ continue;
445
+ }
446
+ changed.set(t.was.id, was);
447
+ out.tasks.push(t.was.id);
448
+ }
449
+ // the marks of review it gave
450
+ for (const x of d.conflicts ?? []) {
451
+ const c = current(x);
452
+ if (!c?.review?.sources.includes(s.id))
453
+ continue;
454
+ const copy = edit(c);
455
+ const left = copy.review.sources.filter((y) => y !== s.id);
456
+ if (left.length)
457
+ copy.review = { ...copy.review, sources: left };
458
+ else
459
+ delete copy.review;
460
+ out.conflicts.push(x);
461
+ }
462
+ const back = { ...s, updated: at };
463
+ delete back.retracted;
464
+ delete back.deleted;
465
+ records.push(back);
466
+ out.restored.push(s.id);
467
+ }
468
+ for (const r of changed.values())
469
+ records.push({ ...r, updated: at });
470
+ tree.putMany(records, [], {
471
+ op: "source.restore",
472
+ targets: [...out.restored, ...changed.keys()],
473
+ summary: `${out.restored.join(", ")} restored by the user: ${out.citations} citation(s) back, ${out.skipped.filter((x) => x.why !== "main").length} skipped`,
474
+ });
475
+ return out;
476
+ });
477
+ }
478
+ /**
479
+ * A conflict whose decision stands though a source it stood on is deleted (strom conflict keep): its mark of review
480
+ * taken off. Refused: an open conflict or one with no mark (conflict.notMarked), none (conflict.unknown).
481
+ */
482
+ export function keepConflict(tree, id) {
483
+ return tree.withTreeLock(() => {
484
+ const c = keepable(tree, id);
485
+ const review = c.review;
486
+ const next = { ...c, updated: now() };
487
+ delete next.review;
488
+ tree.put(next, { op: "conflict.keep", targets: [c.id, ...review.sources], summary: `${c.id} decided as it was, without ${review.sources.join(", ")} (the user)` });
489
+ return next;
490
+ });
491
+ }
492
+ /**
493
+ * The conflict a decision is kept of (strom conflict keep; the bridge checks it before it runs the command): decided,
494
+ * with a mark of review. Refused: none (conflict.unknown), open or with no mark (conflict.notMarked).
495
+ */
496
+ export function keepable(tree, id) {
497
+ const norm = /^X\d+$/iu.test(id.trim()) ? `X${id.trim().slice(1).padStart(4, "0")}` : id.trim();
498
+ const c = tree.get(norm);
499
+ if (!c || c.type !== "conflict" || c.retracted)
500
+ throw new UsageError(`no conflict ${id} in the research`, { hint: "strom conflict list", code: "conflict.unknown", params: { id } });
501
+ if (c.state !== "resolved" || !c.review)
502
+ throw new UsageError(c.state !== "resolved" ? `${c.id} is open: deciding it takes its mark off` : `${c.id} has no mark of review`, { code: "conflict.notMarked", params: { id: c.id } });
503
+ return c;
504
+ }
505
+ /** The mark of a list of impacts (what the person saw): its hash. */
506
+ const markOf = (impacts) => sha256(JSON.stringify(canonicalize(impacts))).slice(0, 32);
507
+ /**
508
+ * The bridge's confirmation of a dry run (POST /source/retract {dryRun: true}): signed with the research's seal key
509
+ * over the sources, the impacts the person was shown and when — "<ms>.<mark>.<signature>".
510
+ */
511
+ export function retractConfirm(key, sources, impacts, at = Date.now()) {
512
+ const mark = markOf(impacts);
513
+ return `${at}.${mark}.${signRecord(key, SOURCE_RETRACT_FEATURE, { sources, impacts: mark, at })}`;
514
+ }
515
+ /**
516
+ * A confirmation checked against the impacts now: `ok`; `changed` — signed, but the research changed since the person
517
+ * saw it (source.retract-changed); `invalid` — none, not signed here, or older than 15 minutes (source.body).
518
+ */
519
+ export function checkRetractConfirm(key, sources, impacts, token, at = Date.now()) {
520
+ if (!key || typeof token !== "string" || token.length > 200)
521
+ return "invalid";
522
+ const m = /^(\d{1,15})\.([0-9a-f]{32})\.([0-9a-f]{64})$/u.exec(token);
523
+ if (!m)
524
+ return "invalid";
525
+ const signed = Number(m[1]);
526
+ if (!(signed <= at + 60_000 && at - signed <= RETRACT_CONFIRM_MS))
527
+ return "invalid";
528
+ if (!verifyRecord(key, SOURCE_RETRACT_FEATURE, { sources, impacts: m[2], at: signed }, m[3]))
529
+ return "invalid";
530
+ return m[2] === markOf(impacts) ? "ok" : "changed";
531
+ }