strom-research 1.30.1 → 1.31.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.
@@ -1,4 +1,4 @@
1
- // check · verify · guard · repair · seal adopt · seal accept · history
1
+ // check · verify · guard · repair · repair undo · seal adopt · seal accept · history
2
2
  import { mb, tidyPlan, TIDY_SAID } from "../core/tidy.js";
3
3
  import { actsAsArchive } from "../core/state.js";
4
4
  import fs from "node:fs";
@@ -8,7 +8,8 @@ import { counted, lines, table } from "../cli/format.js";
8
8
  import { check, SHARED_MISSING, sharedMissing } from "../core/check.js";
9
9
  import { guard } from "../core/guard.js";
10
10
  import { unprovenPeople } from "../core/review.js";
11
- import { AFTER_REPAIR_HINT, NOT_DOWNLOADED, OTHER_KEY, REPAIR_IN_TERMINAL_HINT, SEALED_PATHS, lastSealed, notDownloaded, notDownloadedError, otherKeyError, verifyFast, verifyFull } from "../core/integrity.js";
11
+ import { AFTER_REPAIR_HINT, NOT_DOWNLOADED, OTHER_KEY, otherKeyError, verifyFast, verifyFull } from "../core/integrity.js";
12
+ import { HISTORY_REVERTED, LOST_HINT, REPAIR_ASKS_ABOVE, applyRepair, applyUndo, historyLost, isRecordFile, planRepair, planUndo, quarantines, repairAsks, repairWay, sameRepair } from "../core/repair.js";
12
13
  import { otherKeys } from "../core/seal.js";
13
14
  import { adoptSeal, keysToUnite } from "../cli/seal.js";
14
15
  import { NeedsConsentError, StromError, UsageError } from "../core/errors.js";
@@ -28,6 +29,8 @@ import { receivedPending } from "../core/sync.js";
28
29
  * existing IDs" in a Czech research, after a write a held file stopped); the rest stay strom's own words.
29
30
  */
30
31
  function said(f, lang) {
32
+ if (lang && f.code === HISTORY_REVERTED)
33
+ return ui(lang, "ui.check.lost", { n: f.count ?? 0 });
31
34
  if (lang && f.code === "counter" && f.id)
32
35
  return ui(lang, "ui.check.counter", { prefix: f.id.charAt(0) });
33
36
  if (lang && f.code === "unwritable")
@@ -54,6 +57,8 @@ function said(f, lang) {
54
57
  function hintSaid(f, lang) {
55
58
  if (lang && f.hint === ACCEPT_HINT)
56
59
  return ui(lang, "ui.check.accept.hint");
60
+ if (lang && f.hint === LOST_HINT)
61
+ return ui(lang, "ui.check.lost.hint");
57
62
  if (lang && f.code === "foreign-seal")
58
63
  return ui(lang, "ui.check.foreignseal.hint");
59
64
  if (lang && f.code === OTHER_KEY)
@@ -80,6 +85,14 @@ export function report(findings, okText, lang, person = false) {
80
85
  : lines(table(findings.map((f) => [f.level === "error" ? "ERROR" : "warn", f.code, f.id ?? f.file ?? "", said(f, person ? lang : undefined), f.hint ? `→ ${hintSaid(f, person ? lang : undefined)}` : ""])), "", lang ? ui(lang, "ui.check.found", sum) : `${counted(sum.errors, "error")}, ${counted(sum.warnings, "warning")}`);
81
86
  return { text, data: { ok: errors.length === 0, findings }, exitCode: errors.length ? 1 : 0 };
82
87
  }
88
+ /**
89
+ * The full check of the seals with the way each finding goes: a history (git) that cannot be read — the person's strom
90
+ * seal accept; one older than the research — never strom repair, which would remove that work.
91
+ */
92
+ function sealWay(tree) {
93
+ const full = verifyFull(tree);
94
+ return repairWay(tree, acceptWay(tree, full.findings), full);
95
+ }
83
96
  /**
84
97
  * A research that cannot be written is no "ok" (found on Windows: check said ok where every write failed) — its
85
98
  * .strom and .git tried; what and why strom doctor says.
@@ -109,7 +122,7 @@ register({
109
122
  const lang = agent ? "en" : tree.lang;
110
123
  // the shared folder's files of this research (its material, the images nobody fetches again): only here and in
111
124
  // strom verify, never before a command (each file asked whether it is there)
112
- const checked = report([...acceptWay(tree, verifyFull(tree).findings), ...check(tree), ...guardOrDamaged(tree, () => guard(tree)), ...unwritable(tree, agent), ...sharedMissing(tree)], ui(lang, "ui.check.ok"), lang, !agent);
125
+ const checked = report([...sealWay(tree), ...check(tree), ...guardOrDamaged(tree, () => guard(tree)), ...unwritable(tree, agent), ...sharedMissing(tree)], ui(lang, "ui.check.ok"), lang, !agent);
113
126
  // much kept beside the research that can go (an older strom never tidied it): a sentence, in that language —
114
127
  // none where .strom cannot be listed (found on Windows: a folder denied to strom ended check with "no permission"
115
128
  // instead of its finding; unwritable says it)
@@ -145,7 +158,7 @@ register({
145
158
  options: [{ name: "fast", type: "boolean", description: "only what changed since the last commit (what runs before every write)" }],
146
159
  run(ctx, { opts }) {
147
160
  const tree = ctx.tree();
148
- return report(opts.fast ? verifyFast(tree).findings : [...acceptWay(tree, verifyFull(tree).findings), ...sharedMissing(tree)], "ok — every record matches its seal", isAgent(ctx.env) ? undefined : tree.lang, !isAgent(ctx.env));
161
+ return report(opts.fast ? verifyFast(tree).findings : [...sealWay(tree), ...sharedMissing(tree)], "ok — every record matches its seal", isAgent(ctx.env) ? undefined : tree.lang, !isAgent(ctx.env));
149
162
  },
150
163
  }, {
151
164
  path: ["guard"],
@@ -156,105 +169,41 @@ register({
156
169
  return report(guard(ctx.tree()), "ok — nothing lost since the last commit");
157
170
  },
158
171
  });
159
- function quarantine(tree, rel, stamp) {
160
- const abs = path.join(tree.root, rel);
161
- if (!fs.existsSync(abs))
162
- return;
163
- const dest = path.join(tree.root, ".strom", "quarantine", stamp, rel);
164
- fs.mkdirSync(path.dirname(dest), { recursive: true });
165
- fs.copyFileSync(abs, dest);
166
- }
167
- /** Return data/ and strom.json to the newest sealed commit. */
168
- function repair(tree) {
169
- // files only in iCloud: never written over from the history (the cloud may hold a newer one), their placeholders
170
- // never taken away — downloaded first, then whatever else is wrong is repaired
171
- const cloud = notDownloaded(tree.root);
172
- if (cloud.length)
173
- throw notDownloadedError(cloud);
174
- const key = tree.requireKey();
175
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
176
- const head = git.headInfo(tree.root);
177
- // the newest commit any key of this computer sealed: only what was done outside strom undone, the other key's work
178
- // kept — strom seal adopt unites them after
179
- const { sealed, inTerminal } = lastSealed(tree, key);
180
- if (!sealed)
181
- throw new StromError("no sealed commit found — nothing to restore from", { hint: "ask the user; the history may have been rewritten" });
182
- if (inTerminal)
183
- throw new StromError(`"${tree.config.name}" holds work sealed with the key of the terminal's strom, which this strom (started by an app packaged for Windows) does not see — nothing repaired`, {
184
- hint: REPAIR_IN_TERMINAL_HINT,
185
- code: "seal.repair-in-terminal",
186
- params: { name: tree.config.name },
187
- });
188
- const headSealed = head !== undefined && head.hash === sealed;
189
- // a lock of git's index a git that ended mid-way left (killed with the command that ran it): no git holds it any
190
- // more — taken away, else nothing could be written again (a fresh one may be a git at work: left)
191
- const stale = git.staleIndexLock(tree.root);
192
- if (stale)
193
- fs.rmSync(stale, { force: true });
194
- // Paths to compare: whatever differs between the sealed commit and the working tree.
195
- const candidates = new Set();
196
- // …and what git's index holds otherwise than the last commit (a write taken back after its git add): back to it
197
- const staged = [];
198
- for (const c of git.changes(tree.root, SEALED_PATHS)) {
199
- candidates.add(c.path);
200
- if (!" ?!".includes(c.code[0] ?? " "))
201
- staged.push(c.path);
202
- }
203
- if (!headSealed) {
204
- const r = git.runGit(tree.root, ["diff", "--name-only", "-z", sealed, "HEAD", "--", ...SEALED_PATHS]);
205
- for (const p of r.stdout.split("\0").filter(Boolean))
206
- candidates.add(p);
207
- }
208
- const sealedContent = git.showFiles(tree.root, sealed, [...candidates]);
209
- const restored = [];
210
- const quarantined = [];
211
- for (const rel of [...candidates].sort()) {
212
- const abs = path.join(tree.root, rel);
213
- const want = sealedContent.get(rel);
214
- const have = fs.existsSync(abs) ? fs.readFileSync(abs, "utf8") : undefined;
215
- if (want === have)
216
- continue;
217
- quarantine(tree, rel, stamp);
218
- if (want === undefined) {
219
- fs.rmSync(abs);
220
- quarantined.push(rel);
221
- }
222
- else {
223
- fs.mkdirSync(path.dirname(abs), { recursive: true });
224
- fs.writeFileSync(abs, want);
225
- restored.push(rel);
226
- }
227
- }
228
- // sealed again even when the commits outside strom changed nothing of it (an empty one, notes only): else the last
229
- // commit stays unsealed and every write refused, with nothing left to repair
230
- if (!headSealed)
231
- tree.commit(`Repair: restore the sealed state of ${sealed.slice(0, 8)}\n\nCommits made outside strom were undone for data/, strom.json, history/ and quality/.`, SEALED_PATHS, true);
232
- // the folder as the sealed commit, HEAD: git's index as HEAD too (a commit above put it so already)
233
- else if (staged.length) {
234
- const said = git.unstage(tree.root, staged);
235
- if (said !== undefined)
236
- throw new StromError(`git could not put its index back to the sealed state: ${said}`, {
237
- hint: "programs that may hold the research's folder closed (a sync tool, an antivirus scan, another git), then strom repair again",
238
- code: "repair.index",
239
- details: staged.slice(0, 50),
240
- });
241
- }
242
- return { restored, quarantined, from: sealed, resealed: !headSealed, unstaged: headSealed ? staged.length : 0, lock: !!stale };
243
- }
244
172
  register({
245
173
  path: ["repair"],
246
174
  summary: "Undo changes made outside strom: restore the last sealed state",
247
175
  group: "history",
248
176
  tree: true,
249
177
  description: "Edited records are restored, records created outside strom are removed; copies of everything\n" +
250
- "that was replaced are kept in .strom/quarantine/. Commits made with git directly are undone for data/.\n" +
178
+ "that was replaced are kept in .strom/quarantine/<stamp>/ (strom repair undo <stamp> puts them back). Commits made\n" +
179
+ "with git directly are undone for data/.\n" +
180
+ `Removing more than ${REPAIR_ASKS_ABOVE} records, or records the history says are work rather than changes outside strom\n` +
181
+ "(written by operations sealed in their logs, referred to by other records, older than what the sealed state keeps —\n" +
182
+ "a history (git) older than the research, as a cloud drive leaves it), is the user's own decision in their terminal:\n" +
183
+ "strom repair says what it would remove and asks; an agent, --yes or no terminal gets only the count.\n" +
251
184
  "A tree sealed with two keys of this computer (an app packaged for Windows and a terminal): the work of both kept,\n" +
252
185
  "the keys united after it with strom seal adopt.",
253
- run(ctx) {
186
+ run: async (ctx) => {
254
187
  const tree = ctx.tree();
255
188
  // what a person meets here in the research's language, an agent in English
256
- const lang = isAgent(ctx.env) ? "en" : tree.lang;
257
- const r = tree.withTreeLock(() => repair(tree));
189
+ const agent = isAgent(ctx.env);
190
+ const lang = agent ? "en" : tree.lang;
191
+ const asked = planRepair(tree);
192
+ const asks = repairAsks(asked);
193
+ if (asks) {
194
+ const set = "strom repair";
195
+ ctx.requireHuman(repairQuestion(asked), set, "repair", lines(repairSaid(asked, lang), "", ui(lang, "ui.repair.person", { command: set })), { window: false });
196
+ ctx.io.stdout(repairSaid(asked, lang) + "\n");
197
+ if (!(await ctx.confirm(ui(lang, "ui.repair.ask", { n: asked.records.length }), false)))
198
+ return { text: ui(lang, "ui.cancelled"), data: { ...repairData(asked), repaired: false } };
199
+ }
200
+ const r = tree.withTreeLock(() => {
201
+ // under the lock: what it would do now — anything changed since the look (or since the person's yes), nothing done
202
+ const plan = planRepair(tree);
203
+ if (!sameRepair(plan, asked) || (!asks && repairAsks(plan)))
204
+ throw new StromError("the research changed since it was looked over — nothing repaired", { hint: "strom repair (looks it over again)", code: "repair.changed" });
205
+ return applyRepair(tree, plan);
206
+ });
258
207
  // the work of another key of this computer kept: united next, by the person in their terminal (no problem left of
259
208
  // what strom repair undoes)
260
209
  const after = verifyFast(tree).findings.filter((f) => f.level === "error" && f.code !== OTHER_KEY);
@@ -268,9 +217,62 @@ register({
268
217
  : index.length
269
218
  ? lines(...index, after.length ? ui(lang, "ui.repair.still", { n: after.length }) : next)
270
219
  : lines(ui(lang, "ui.repair.nothing"), next)
271
- : lines(...index, ...r.restored.map((file) => ui(lang, "ui.repair.restored", { file })), ...r.quarantined.map((file) => ui(lang, "ui.repair.removed", { file })), ui(lang, "ui.repair.from", { commit: r.from.slice(0, 8) }), after.length ? ui(lang, "ui.repair.still", { n: after.length }) : next);
220
+ : lines(...index, ...r.restored.map((file) => ui(lang, "ui.repair.restored", { file })), ...r.quarantined.map((file) => ui(lang, "ui.repair.removed", { file })), ui(lang, "ui.repair.from", { commit: r.from.slice(0, 8) }), r.stamp ? ui(lang, "ui.repair.undo.how", { command: `strom repair undo ${r.stamp}` }) : undefined, after.length ? ui(lang, "ui.repair.still", { n: after.length }) : next);
272
221
  return { text, data: { ...r, ok: after.length === 0, ...(unite ? { unite: "strom seal adopt" } : {}) }, exitCode: after.length ? 1 : 0 };
273
222
  },
223
+ }, {
224
+ path: ["repair", "undo"],
225
+ summary: "Put back what strom repair removed or replaced (the user runs this in a terminal)",
226
+ group: "history",
227
+ tree: true,
228
+ args: [{ name: "stamp", description: "the folder of .strom/quarantine/ strom repair named (without it: the list)" }],
229
+ description: "strom repair keeps a copy of every file it removed or wrote over in .strom/quarantine/<stamp>/. Without a stamp: the\n" +
230
+ "copies kept, newest first (read only, anyone may). With one: says what it would put back — a file removed and not\n" +
231
+ "there since, a file written back and not changed since; anything changed since is left as it is now, a file strom\n" +
232
+ "does not seal stays in the quarantine. On the user's yes, one sealed operation names each record put back as it is;\n" +
233
+ "nothing in the folder is deleted. Only onto a research as strom sealed it (strom verify clean). Putting back is the\n" +
234
+ "user's own decision at their terminal — an agent tells the user the command, never runs it.",
235
+ examples: ["strom repair undo", "strom repair undo 2026-11-09T18-02-11-123Z"],
236
+ person: "Putting back what strom repair removed is the user's own decision, in their terminal",
237
+ agentMay: { when: "without a stamp (the list)", check: (_ctx, { args }) => args.length === 0 },
238
+ run: async (ctx, { args }) => {
239
+ const tree = ctx.tree();
240
+ const agent = isAgent(ctx.env);
241
+ const lang = agent ? "en" : tree.lang;
242
+ const stamp = args[0];
243
+ if (!stamp) {
244
+ const list = quarantines(tree.root);
245
+ if (!list.length)
246
+ return { text: ui(lang, "ui.repair.undo.none"), data: { quarantines: [] } };
247
+ return {
248
+ text: lines(ui(lang, "ui.repair.undo.list"), ...list.map((q) => ui(lang, "ui.repair.undo.item", { stamp: q.stamp, n: q.files, records: q.records }))),
249
+ data: { quarantines: list },
250
+ };
251
+ }
252
+ const set = `strom repair undo ${stamp}`;
253
+ const plan = planUndo(tree, stamp);
254
+ const data = undoData(plan);
255
+ const said = undoSaid(plan, lang);
256
+ if (plan.back.length === 0)
257
+ return { text: lines(said, ui(lang, "ui.repair.undo.nothing")), data: { ...data, undone: false, nothing: true } };
258
+ if (!ctx.interactive)
259
+ return { text: lines(said, "", ui(lang, "ui.repair.undo.person", { command: set })), data: { ...data, undone: false, run: set }, exitCode: 4 };
260
+ if (liveRunning(tree.root))
261
+ throw new UsageError("the bridge to the Strom app runs on this research: nothing put back", { hint: `strom live stop, then ${set}`, code: "repair.undo-bridge" });
262
+ if (liveWorkers(tree.root).length > 0 || runsAtWork(tree.root).length > 0)
263
+ throw new UsageError("somebody is at work on this research: putting back only once they finished", { hint: `strom session finish, then ${set}`, code: "repair.undo-busy" });
264
+ ctx.requireHuman("Put back what strom repair removed (a sealed change)?", set, "repair", ui(lang, "ui.repair.undo.person", { command: set }), { window: false });
265
+ ctx.io.stdout(said + "\n");
266
+ if (!(await ctx.confirm(ui(lang, "ui.repair.undo.ask"), false)))
267
+ return { text: ui(lang, "ui.cancelled"), data: { ...data, undone: false } };
268
+ const r = applyUndo(tree, plan);
269
+ const after = verifyFull(tree).findings.filter((f) => f.level === "error");
270
+ return {
271
+ text: lines(ui(lang, "ui.repair.undo.done", { n: r.back, records: r.records }), after.length ? ui(lang, "ui.repair.still", { n: after.length }) : ui(lang, "ui.accept.verified")),
272
+ data: { ...data, undone: true, commit: r.commit, verify: { ok: after.length === 0, errors: after.length } },
273
+ exitCode: after.length ? 1 : 0,
274
+ };
275
+ },
274
276
  }, {
275
277
  path: ["seal", "adopt"],
276
278
  summary: "Take over a tree sealed on another computer (the user runs this in a terminal)",
@@ -485,3 +487,31 @@ function acceptData(plan) {
485
487
  refused: plan.refused.length,
486
488
  };
487
489
  }
490
+ /** What strom repair would remove, as a person reads it before saying yes. */
491
+ function repairSaid(plan, lang) {
492
+ const first = (l) => l[0] ?? "";
493
+ return lines(ui(lang, "ui.repair.ask.title", { n: plan.records.length, files: plan.remove.length, back: plan.restore.length, commit: plan.from.slice(0, 8) }), plan.sealedWork.length ? ui(lang, "ui.repair.ask.sealed", { n: plan.sealedWork.length }) : undefined, plan.referenced.length ? ui(lang, "ui.repair.ask.referenced", { n: plan.referenced.length, first: first(plan.referenced) }) : undefined, plan.older.length ? ui(lang, "ui.repair.ask.older", { n: plan.older.length, first: first(plan.older) }) : undefined, plan.cloudCopies.length ? ui(lang, "ui.repair.ask.copies", { n: plan.cloudCopies.length, list: plan.cloudCopies.slice(0, 3).join(", ") }) : undefined, "", ui(lang, "ui.repair.ask.backup"), historyLost(plan) ? ui(lang, "ui.repair.ask.lost") : undefined);
494
+ }
495
+ /** The question an agent (or a program) reads where strom repair waits for the person: what it would remove, in English. */
496
+ function repairQuestion(plan) {
497
+ const n = plan.records.length;
498
+ const why = [
499
+ plan.sealedWork.length ? `${plan.sealedWork.length} written by operations sealed in their logs` : "",
500
+ plan.referenced.length ? `${plan.referenced.length} referred to by other records` : "",
501
+ plan.older.length ? `${plan.older.length} older than what the sealed state keeps` : "",
502
+ ].filter(Boolean);
503
+ return (`strom repair would remove ${n} ${n === 1 ? "record" : "records"}${why.length ? ` (${why.join(", ")})` : ""} — the whole research folder backed up first` +
504
+ (historyLost(plan) ? "; the history (git) looks older than the research: rather .git put back from a backup or Time Machine, or, once the records are looked over, strom seal accept" : "") +
505
+ ". Remove them?");
506
+ }
507
+ function repairData(plan) {
508
+ return { from: plan.from, records: plan.records, remove: plan.remove.length, restore: plan.restore.length, sealedWork: plan.sealedWork.length, referenced: plan.referenced, older: plan.older.length, cloudCopies: plan.cloudCopies, historyLost: historyLost(plan) };
509
+ }
510
+ /** What strom repair undo would put back, as a person reads it. */
511
+ function undoSaid(plan, lang) {
512
+ const records = plan.back.filter((f) => isRecordFile(f.path)).length;
513
+ return lines(ui(lang, "ui.repair.undo.title", { stamp: plan.stamp }), ui(lang, "ui.repair.undo.back", { n: plan.back.length, records }), plan.kept.length ? ui(lang, "ui.repair.undo.kept", { n: plan.kept.length, first: plan.kept[0] }) : undefined, plan.left.length ? ui(lang, "ui.repair.undo.left", { n: plan.left.length }) : undefined, plan.back.length ? ui(lang, "ui.repair.undo.does") : undefined);
514
+ }
515
+ function undoData(plan) {
516
+ return { stamp: plan.stamp, back: plan.back.map((f) => f.path), kept: plan.kept, same: plan.same.length, left: plan.left };
517
+ }
@@ -37,7 +37,7 @@ import { PROFILES } from "../agents/profiles.js";
37
37
  import { bareHost, byHandOnly, changedSinceConsent, codeWarning, consentRequired, connectorHash, connectorsDir, directNetwork, ensurePluginsDir, findConnector, hostWarning, imageProblem, INTERFACE, listConnectors, loadConsents, lockedCode, MANIFEST, missingConsents, NAME_RE, readManifest, routeOf, sandboxedRun, treeBrowserConnectors, routesOf, ROUTES, runConnector, saveConsents, scanConnectors, suggestName, } from "../core/connector.js";
38
38
  import { registerImages, wakeWaiting } from "./media.js";
39
39
  import { autoCommit } from "../cli/commit.js";
40
- import { activeFetches, askStop, BACKGROUND_ENV, backgroundLog, backgroundOf, endedFetches, FETCH_BATCH, FETCH_SILENT_MS, isRunWorker, markEnded, markFetch, processAlive, watchBackground, withRegistered } from "../core/fetching.js";
40
+ import { activeFetches, askStop, BACKGROUND_ENV, backgroundLog, backgroundOf, BOOK_GUESS, endedFetches, FETCH_BATCH, FETCH_SILENT_MS, HEAVY_IMAGE, heavySaid, isRunWorker, markEnded, markFetch, processAlive, spanSaid, watchBackground, withRegistered } from "../core/fetching.js";
41
41
  import { finishAsked } from "../core/clock.js";
42
42
  import { isLiveWorker } from "../core/workers.js";
43
43
  import { stromLauncher } from "../core/self.js";
@@ -1740,19 +1740,6 @@ async function testWith(ctx, c, request, max) {
1740
1740
  ...(later(r, "the same command").exitCode ? { exitCode: EXIT.later } : r.stopped && !r.books.length && !r.images.length && !r.located.length ? { exitCode: 1 } : {}),
1741
1741
  };
1742
1742
  }
1743
- /** More requests than this for one whole image: tiles, most likely — hours for a book (DISCOVERY.md, step 2). */
1744
- export const HEAVY_IMAGE = 10;
1745
- /** A book of this many images, for the time a book takes when the book's own number is not known here. */
1746
- const BOOK_GUESS = 200;
1747
- /** A time said: seconds, minutes, else hours. */
1748
- function spanSaid(ms) {
1749
- const secs = Math.round(ms / 1000);
1750
- if (secs < 90)
1751
- return `${secs} s`;
1752
- if (secs < 90 * 60)
1753
- return `${Math.round(secs / 60)} min`;
1754
- return `${Math.round(secs / 360) / 10} h`;
1755
- }
1756
1743
  /**
1757
1744
  * A test's fetch whose one image cost more than HEAVY_IMAGE requests (as this run's measure counted them: what went to
1758
1745
  * the archive's hosts), or that got no image whole within a cap past it: said to the agent with what it means for a
@@ -1766,21 +1753,67 @@ function heavyImage(ctx, c, book, r, sent, max, human) {
1766
1753
  if (got ? sent / got <= HEAVY_IMAGE : !capped)
1767
1754
  return undefined;
1768
1755
  const per = got ? sent / got : undefined;
1769
- const least = per ?? max;
1756
+ const cost = heavyCost(ctx, c, per ?? max, per === undefined, bookImagesOf(ctx, c, book, r.books), human);
1757
+ return {
1758
+ text: lines(`⚠ ${per !== undefined ? `one image cost ${nf(per)} requests` : `not one image whole within ${max} requests: one costs more (--max up to 50 to see how many)`} ${cost.said}`, " before tiles look again for one request an image (DISCOVERY.md, step 2): the portal's own link to the full image, a download of the whole book (ZIP, PDF), a IIIF image (full/max)", " tiles only when nothing else exists: then say in README.md what an image costs, and tell the user how long a book takes"),
1759
+ data: { ...(per !== undefined ? { perImage: cost.data.perImage } : { atLeast: max }), ...(cost.data.bookImages !== undefined ? { bookImages: cost.data.bookImages } : {}), bookMs: cost.data.bookMs },
1760
+ };
1761
+ }
1762
+ /**
1763
+ * What an image of `least` requests means at the connector's pace (`atLeast`: it costs more than that): the rest of
1764
+ * the sentence after the cost ("(tiles, most likely) — at its pace … an image, … for a book"), and its data. `size`:
1765
+ * the book's own number of images where it is known, else a book of BOOK_GUESS.
1766
+ */
1767
+ function heavyCost(ctx, c, least, atLeast, size, human) {
1770
1768
  const pace = connectorPace(ctx, c, human);
1771
- const size = bookImagesOf(ctx, c, book, r);
1772
- const n = size ?? BOOK_GUESS;
1773
- const bookMs = requestsSpan(Math.ceil(least * n), pace, [], 0);
1769
+ const bookMs = requestsSpan(Math.ceil(least * (size ?? BOOK_GUESS)), pace, [], 0);
1774
1770
  const imageMs = requestsSpan(Math.ceil(least) + 1, pace, [], 0);
1775
- const cost = per !== undefined ? `one image cost ${nf(per)} requests` : `not one image whole within ${max} requests: one costs more (--max up to 50 to see how many)`;
1776
1771
  return {
1777
- text: lines(`⚠ ${cost} (tiles, most likely) — at its pace (${paceText(pace)}) ${per !== undefined ? "about" : "at least"} ${spanSaid(imageMs)} an image, ${spanSaid(bookMs)} for ${size !== undefined ? `this book's ${size} images` : `a book of ${BOOK_GUESS} images`}`, " before tiles look again for one request an image (DISCOVERY.md, step 2): the portal's own link to the full image, a download of the whole book (ZIP, PDF), a IIIF image (full/max)", " tiles only when nothing else exists: then say in README.md what an image costs, and tell the user how long a book takes"),
1778
- data: { ...(per !== undefined ? { perImage: Math.round(per * 100) / 100 } : { atLeast: max }), ...(size !== undefined ? { bookImages: size } : {}), bookMs },
1772
+ said: `(tiles, most likely) — at its pace (${paceText(pace)}) ${atLeast ? "at least" : "about"} ${spanSaid(imageMs)} an image, ${spanSaid(bookMs)} for ${size !== undefined ? `this book's ${size} images` : `a book of ${BOOK_GUESS} images`}`,
1773
+ data: { perImage: Math.round(least * 100) / 100, ...(size !== undefined ? { bookImages: size } : {}), bookMs },
1774
+ };
1775
+ }
1776
+ /**
1777
+ * strom fetch's own image of many requests (tiles, most likely), said to the agent once a run as connector test says
1778
+ * it — a connector built before that test said it goes on without a word otherwise. From the run's own measure
1779
+ * (FetchMeter): from its second image what each image after the first cost (a manifest, robots.txt asked once at the
1780
+ * start are no image's), a run of one image at its end; nothing is asked of the archive for it. Said on stderr (a
1781
+ * fetch in the background: into its log), its mark carries it (strom fetch --status, the brief), the result's data too.
1782
+ */
1783
+ function heavyFetch(ctx, c, request, recordset, meter, human, say, background) {
1784
+ let first;
1785
+ let found;
1786
+ const tell = (per, books) => {
1787
+ if (found || per <= HEAVY_IMAGE)
1788
+ return;
1789
+ const book = String(request.book);
1790
+ const own = recordset ? ctx.tree().get(recordset)?.images : undefined;
1791
+ const size = Number.isInteger(own) && own > 0 ? own : bookImagesOf(ctx, c, book, books);
1792
+ const cost = heavyCost(ctx, c, per, false, size, human);
1793
+ found = cost.data;
1794
+ say(lines(` ⚠ connector ${c.name}: one image costs ${nf(per)} requests ${cost.said}`, ` this fetch goes on at that pace${background && recordset ? ` in the background — stop it: strom fetch --stop ${recordset}` : ""}`, ` a connector of one request an image first (DISCOVERY.md, step 2): the portal's own link to the full image, a download of the whole book (ZIP, PDF), a IIIF image (full/max) — then strom connector test ${c.name} --fetch ${shellArg(book)} --images 1`) + "\n");
1795
+ return found;
1796
+ };
1797
+ return {
1798
+ /** An image came (`got`: how many so far): from the second on, what one costs. */
1799
+ image(got) {
1800
+ if (found)
1801
+ return undefined;
1802
+ if (got <= 1) {
1803
+ first = meter.requests();
1804
+ return undefined;
1805
+ }
1806
+ return first === undefined ? undefined : tell((meter.requests() - first) / (got - 1), []);
1807
+ },
1808
+ /** The run ended: one image only — what the whole run cost. */
1809
+ end(r) {
1810
+ return !found && r.images.length === 1 ? tell(meter.requests() + (r.pages ?? 0) || r.requests, r.books) : undefined;
1811
+ },
1779
1812
  };
1780
1813
  }
1781
1814
  /** How many images a book of a connector has, as this run (a book it gave) or the research (a record set of it) knows. */
1782
- function bookImagesOf(ctx, c, book, r) {
1783
- const given = r.books.find((b) => b.id === book && Number.isInteger(b.images) && b.images > 0)?.images;
1815
+ function bookImagesOf(ctx, c, book, books) {
1816
+ const given = books.find((b) => b.id === book && Number.isInteger(b.images) && b.images > 0)?.images;
1784
1817
  if (given)
1785
1818
  return given;
1786
1819
  if (!ctx.hasTree())
@@ -2217,6 +2250,10 @@ function fetchBatches(ctx, c, request, recordset, from, child, task, workDir) {
2217
2250
  waiting(until) {
2218
2251
  mark.beat({ waitUntil: until });
2219
2252
  },
2253
+ /** One image costs many requests (tiles): its mark says it (strom fetch --status, the brief). */
2254
+ heavy(h) {
2255
+ mark.beat({ registered: done.size, heavy: h });
2256
+ },
2220
2257
  /** The run is over: what it gave and no batch holds is registered; a placeholder an earlier batch took withdrawn. */
2221
2258
  finish(images) {
2222
2259
  const kept = new Set(images.map((i) => i.file));
@@ -2485,7 +2522,8 @@ async function joinFetch(ctx, recordset, joined, said) {
2485
2522
  function activeLine(m) {
2486
2523
  const since = m.since ? ` · since ${clock(Date.parse(m.since))}` : "";
2487
2524
  const state = m.waitUntil && m.waitUntil > Date.now() ? ` · waits for the archive until ${clockUp(m.waitUntil)}, then goes on by itself` : m.yielding ? " · waits while a fetch in the foreground asks the archive" : "";
2488
- return `${m.recordset} (${m.connector} ${m.book}): ${m.registered}/${m.images.length} images registered · ${m.background ? `in the background${m.task ? ` for ${m.task}` : ""}${m.session ? ` (session ${m.session})` : ""}` : "in the foreground"}${since}${state} · pid ${m.pid}`;
2525
+ const heavy = m.heavy ? ` · ${heavySaid(m.heavy, m.background ? `strom fetch --stop ${m.recordset}` : undefined)}` : "";
2526
+ return `${m.recordset} (${m.connector} ${m.book}): ${m.registered}/${m.images.length} images registered · ${m.background ? `in the background${m.task ? ` for ${m.task}` : ""}${m.session ? ` (session ${m.session})` : ""}` : "in the foreground"}${since}${state} · pid ${m.pid}${heavy}`;
2489
2527
  }
2490
2528
  function endedLine(e) {
2491
2529
  // ended without a word (its process killed, the computer stopped): found so by a later strom, its last sign of life
@@ -2493,7 +2531,7 @@ function endedLine(e) {
2493
2531
  ? ` · ${e.background ? "in the background" : "in the foreground"}, last heard ${clock(Date.parse(e.at))} — interrupted: ${e.interrupted === "gone" ? `its process (pid ${e.pid}) ended without a word (killed, or the computer stopped)` : `nothing heard of it for ${FETCH_SILENT_MS / 60_000} min (pid ${e.pid})`}`
2494
2532
  : ` · ended ${clock(Date.parse(e.at))}${e.stopped ? ` — stopped: ${e.stopped}` : e.exitCode ? ` — exit ${e.exitCode}` : ""}`;
2495
2533
  const again = `strom fetch ${e.connector} ${shellArg(e.book)} --images ${imagesArg(e.missed)} --recordset ${e.recordset}${e.interrupted && e.background ? " --background" : ""}`;
2496
- return `${e.recordset} (${e.connector} ${e.book}): ${e.registered.length}/${e.images.length} images registered${e.registered.length ? ` (images ${runs(e.registered)})` : ""}${how}${e.missed.length ? ` · not fetched: images ${runs(e.missed)} (${again}${e.interrupted ? " — what is registered is not fetched again" : ""})` : ""}`;
2534
+ return `${e.recordset} (${e.connector} ${e.book}): ${e.registered.length}/${e.images.length} images registered${e.registered.length ? ` (images ${runs(e.registered)})` : ""}${how}${e.missed.length ? ` · not fetched: images ${runs(e.missed)} (${again}${e.interrupted ? " — what is registered is not fetched again" : ""})` : ""}${e.heavy ? ` · ${heavySaid(e.heavy)}` : ""}`;
2497
2535
  }
2498
2536
  /** strom fetch --status: what is being fetched for this research now, and the fetches in the background that ended lately. */
2499
2537
  function fetchStatus(ctx, names) {
@@ -2652,6 +2690,15 @@ async function fetchWith(ctx, c, request, recordset, noIndex = false, again = fa
2652
2690
  const from = (f) => `connector ${c.name} · ${path.basename(f)}`;
2653
2691
  // the images of a book registered as they come, in batches: a reader of the book begins on the first ones
2654
2692
  const batches = request.cmd === "fetch" && recordset ? fetchBatches(ctx, c, request, recordset, from, child, forTask, workDir) : undefined;
2693
+ // an image of many requests (tiles): said once a run, as connector test says it (the run's own measure)
2694
+ const heavy = request.cmd === "fetch" ? heavyFetch(ctx, c, request, recordset, meter, gate.human, count.say, !!child) : undefined;
2695
+ let found;
2696
+ const costly = (h) => {
2697
+ if (!h)
2698
+ return;
2699
+ found = h;
2700
+ batches?.heavy(h);
2701
+ };
2655
2702
  let endCode;
2656
2703
  // why the connector stopped before the end (an error of it, a refusal, a host gone silent) — not a Ctrl-C
2657
2704
  let cut;
@@ -2661,7 +2708,7 @@ async function fetchWith(ctx, c, request, recordset, noIndex = false, again = fa
2661
2708
  workDir,
2662
2709
  netDir: netDir(ctx),
2663
2710
  onLog: (l) => count.say(` · ${l}\n`),
2664
- onImage: (n, im) => (count.got(n), batches?.took(im)),
2711
+ onImage: (n, im) => (count.got(n), batches?.took(im), costly(heavy?.image(n))),
2665
2712
  waitMs: waits.waitMs,
2666
2713
  onWait: (w) => (count.clear(), batches?.waiting(w.until), waits.onWait(w)),
2667
2714
  ...metered(meter),
@@ -2672,6 +2719,7 @@ async function fetchWith(ctx, c, request, recordset, noIndex = false, again = fa
2672
2719
  ...(child ? { background: true, onYield: (w) => batches?.yielding(w) } : {}),
2673
2720
  });
2674
2721
  count.clear();
2722
+ costly(heavy?.end(r));
2675
2723
  if (r.stopped && !batches?.interrupted())
2676
2724
  cut = r.stopped;
2677
2725
  refusalSaid(ctx, c, r.refused);
@@ -2766,7 +2814,7 @@ async function fetchWith(ctx, c, request, recordset, noIndex = false, again = fa
2766
2814
  // the connector stopped with images left: no success — the output says which and how to go on (a refusal: its own advice, as before)
2767
2815
  const code = wait.exitCode ? wait.exitCode : batches?.stopped() ? 0 : batches?.interrupted() ? EXIT.cancelled : r.stopped && (!r.images.length || (missed.length && !r.refused)) ? EXIT.error : after?.exitCode;
2768
2816
  endCode = code ?? 0;
2769
- return { text: lines(describeRun(r, request.cmd), text, advice, wait.line, near, after?.text), data: { ...data, ...wait.data, ...(after ? { joined: after.data } : {}) }, ...(code ? { exitCode: code } : {}) };
2817
+ return { text: lines(describeRun(r, request.cmd), text, advice, wait.line, near, after?.text), data: { ...data, ...wait.data, ...(after ? { joined: after.data } : {}), ...(found ? { heavy: found } : {}) }, ...(code ? { exitCode: code } : {}) };
2770
2818
  }
2771
2819
  finally {
2772
2820
  // a fetch in the background says how it ended (strom fetch --status, the next brief) before its mark goes; one in
@@ -2793,6 +2841,7 @@ async function fetchWith(ctx, c, request, recordset, noIndex = false, again = fa
2793
2841
  since: new Date(t0).toISOString(),
2794
2842
  ...(session ? { session } : {}),
2795
2843
  ...(child?.task ? { task: child.task } : {}),
2844
+ ...(found ? { heavy: found } : {}),
2796
2845
  exitCode: endCode ?? 1,
2797
2846
  });
2798
2847
  }
@@ -483,10 +483,14 @@ register({
483
483
  tree: true,
484
484
  async run(ctx) {
485
485
  const tree = bridgeTree(ctx);
486
- await serveLive(tree.root, ctx.env);
486
+ const held = await serveLive(tree.root, ctx.env);
487
487
  // a bridge that ended is gone as a process, whatever still holds it (found on Mac: bridges of folders long removed
488
488
  // still running, nobody to follow them)
489
489
  setTimeout(() => process.exit(), 3000).unref();
490
+ // ended for another bridge of the tree (exit EXIT.locked): the bridge that started it to take over knows it from
491
+ // a start that failed
492
+ if (held)
493
+ return { text: ui(tree.lang, "ui.live.ended"), data: { heldBy: held }, exitCode: EXIT.locked };
490
494
  return { text: ui(tree.lang, "ui.live.ended"), data: {} };
491
495
  },
492
496
  }, {
@@ -43,7 +43,7 @@ import { webDomain } from "../core/metrics.js";
43
43
  import { permissionWait } from "../core/archivewait.js";
44
44
  import { WAIT_KINDS } from "../core/model.js";
45
45
  import { SENDABLE, waitKindOf, waitState } from "../core/waitkind.js";
46
- import { requestNote } from "../core/waiting.js";
46
+ import { requestNote, requestPath } from "../core/waiting.js";
47
47
  import { addressesPerson } from "../core/impersonal.js";
48
48
  function written(tree) {
49
49
  return lines(...tree.written.map((o) => o.summary));
@@ -531,23 +531,8 @@ function waitOptions(tree, id, opts, has = {}) {
531
531
  }
532
532
  if (typeof opts.to === "string" && opts.to.trim())
533
533
  wait.to = impersonal(tree, "--to", opts.to).slice(0, 300);
534
- if (opts.request !== undefined) {
535
- const raw = String(opts.request).trim();
536
- const parts = raw.split(/[\\/]+/);
537
- // a path of the tree's notes/, as given (never normalized): no absolute path, no way out of notes/
538
- if (!raw || path.isAbsolute(raw) || /^[A-Za-z]:/.test(raw) || parts[0] !== "notes" || parts.length < 2 || parts.some((p) => p === ".." || p === "."))
539
- throw new UsageError(`--request takes a file of the tree's notes/, as notes/<file>.md — not "${raw}"`, { hint: `save the request's text first (notes/request-<what>.md), then strom task wait ${id} … --request notes/request-<what>.md` });
540
- let file = false;
541
- try {
542
- file = fs.statSync(path.join(tree.root, ...parts)).isFile();
543
- }
544
- catch {
545
- file = false;
546
- }
547
- if (!file)
548
- throw new UsageError(`--request: no file ${raw} in this tree`, { hint: `save the request's text there first, then name it again`, code: "task.request-missing" });
549
- wait.note = parts.join("/");
550
- }
534
+ if (opts.request !== undefined)
535
+ wait.note = requestPath(tree.root, String(opts.request), id);
551
536
  if (opts.url !== undefined) {
552
537
  if (has.check)
553
538
  throw new UsageError("--url with --check: --check carries the site's address itself", { hint: "leave out --url" });