@gentbajko/slopify 4.5.2 → 4.5.3

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 (41) hide show
  1. package/dist/extension/slopify-studio-chrome.zip +0 -0
  2. package/dist/extension/slopify-studio-firefox.zip +0 -0
  3. package/dist/kernel/db/migrations/0079-plan-history-indexes.sql +11 -0
  4. package/dist/kernel/db/migrations/0080-attempts-work-index.sql +4 -0
  5. package/dist/kernel/runner/providers.js +1 -1
  6. package/dist/kernel/runner/queue.js +31 -5
  7. package/dist/kernel/runner/work.js +52 -1
  8. package/dist/main.js +1 -1
  9. package/dist/patch-notes/4.5.3.md +16 -0
  10. package/dist/patch-notes/index.json +6 -0
  11. package/dist/slices/loudness/level-pieces.js +12 -8
  12. package/dist/slices/loudness/sentence-level.js +35 -24
  13. package/dist/slices/narration/breaths-worker.js +126 -0
  14. package/dist/slices/narration/breaths.js +19 -81
  15. package/dist/slices/narration/clean-pieces.js +9 -10
  16. package/dist/slices/narration/pauses.js +18 -17
  17. package/dist/slices/narration/piece-jobs.js +54 -0
  18. package/dist/slices/narration/pronunciation.js +48 -3
  19. package/dist/slices/rebuild/admission-repo.js +14 -1
  20. package/dist/slices/rebuild/narration-history.js +72 -23
  21. package/dist/slices/rebuild/narration-reuse.js +16 -5
  22. package/dist/slices/rebuild/provided-review.js +14 -4
  23. package/dist/slices/rebuild/recipe-document.js +23 -17
  24. package/dist/slices/rebuild/recipe-exports.js +8 -1
  25. package/dist/slices/rebuild/recipe-model.js +48 -4
  26. package/dist/slices/rebuild/recipe-preparation.js +28 -6
  27. package/dist/slices/rebuild/recipe-reviews.js +28 -24
  28. package/dist/slices/rebuild/recovery.js +35 -2
  29. package/dist/slices/rebuild/review-redo.js +15 -7
  30. package/dist/slices/rebuild/runtime-admission.js +5 -0
  31. package/dist/slices/rebuild/runtime-agent-review.js +4 -2
  32. package/dist/slices/rebuild/runtime-materialize.js +14 -0
  33. package/dist/slices/rebuild/runtime-plan.js +86 -40
  34. package/dist/slices/rebuild/runtime-review.js +3 -2
  35. package/dist/slices/rebuild/transition-repo.js +13 -10
  36. package/dist/slices/reviews/outcome.js +5 -3
  37. package/dist/slices/reviews/repo.js +12 -0
  38. package/dist/slices/revisions/view.js +3 -3
  39. package/dist/slices/settings/model.js +6 -2
  40. package/dist/slices/storage/layout.js +15 -0
  41. package/package.json +1 -1
@@ -5,6 +5,7 @@ import { editSettings } from "../../kernel/ports/settings-places.js";
5
5
  import { runFfmpeg } from "../video/ffmpeg.js";
6
6
  import { softenBreaths } from "./breaths.js";
7
7
  import { deEsser } from "./breaths-model.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  export async function cleanPieces(run, files, directory, cleaning) {
9
10
  if (!cleaning.breaths && !cleaning.deEss)
10
11
  return undefined;
@@ -22,27 +23,25 @@ export async function cleanPieces(run, files, directory, cleaning) {
22
23
  }
23
24
  export async function deEssPieces(run, files, directory) {
24
25
  mkdirSync(directory, { recursive: true, mode: 0o700 });
25
- const written = [];
26
- for (const [index, file] of files.entries()) {
27
- run.signal.throwIfAborted();
26
+ // Several pieces at once, in order (`piece-jobs.ts`).
27
+ return mapPieces(run, files, async (file, index, own) => {
28
28
  const output = join(directory, `deess-${String(index + 1).padStart(4, "0")}.wav`);
29
29
  try {
30
30
  await runFfmpeg({
31
- bin: run.bin,
31
+ bin: own.bin,
32
32
  args: deEssArgs(file, output),
33
- signal: run.signal,
34
- log: run.log,
33
+ signal: own.signal,
34
+ log: own.log,
35
35
  onProgress: () => { },
36
36
  });
37
37
  }
38
38
  catch (error) {
39
- if (run.signal.aborted)
39
+ if (own.signal.aborted)
40
40
  throw error;
41
41
  throw new Error(`Soften S sounds could not process narration piece ${String(index + 1)} (${errorText(error)}), so the narration can't be joined together. Use Try again; if it fails again, turn off Soften S sounds in ${editSettings.sound} and use Save changes, then use Download diagnostics in Settings and report it.`, { cause: error });
42
42
  }
43
- written.push(output);
44
- }
45
- return written;
43
+ return output;
44
+ });
46
45
  }
47
46
  export function deEssFilter() {
48
47
  return `deesser=i=${String(deEsser.intensity)}:m=${String(deEsser.max)}:f=${String(deEsser.frequency)}`;
@@ -5,6 +5,7 @@ import { measureFile } from "../loudness/loudnorm.js";
5
5
  import { pieceLufs, pieceTruePeak } from "../loudness/model.js";
6
6
  import { probeDurationMs, runFfmpeg } from "../video/ffmpeg.js";
7
7
  import { sentences } from "./chunk.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  // How long a stretch of text takes to say, in letters. Digits count as their words ("1982" as
9
10
  // "nineteen eighty two", English's being a fair measure for any language's), an IPA spelling's
10
11
  // slashes and stress marks count nothing, and a run of spacing counts one. Counted as written,
@@ -244,17 +245,16 @@ export async function measurePiece(run, file) {
244
245
  // Every piece's plan, from the pieces as spoken: silences inside, and at each piece's end what
245
246
  // the gap to the next piece lacks.
246
247
  export async function planPieces(run, pieces, settings) {
247
- const measured = [];
248
- for (const piece of pieces) {
249
- run.signal.throwIfAborted();
250
- const { durationSeconds, silences } = await measurePiece(run, piece.file);
251
- measured.push(planPauses({
248
+ // Measured several pieces at once, in order (`piece-jobs.ts`).
249
+ const measured = await mapPieces(run, pieces, async (piece, _index, own) => {
250
+ const { durationSeconds, silences } = await measurePiece(own, piece.file);
251
+ return planPauses({
252
252
  durationSeconds,
253
253
  silences,
254
254
  boundaries: textBoundaries(piece.text),
255
255
  settings,
256
- }));
257
- }
256
+ });
257
+ });
258
258
  return measured.map((pauses, at) => {
259
259
  const piece = pieces[at];
260
260
  const following = measured[at + 1];
@@ -269,25 +269,26 @@ export async function planPieces(run, pieces, settings) {
269
269
  // the spoken pieces.
270
270
  export async function applyPauses(run, files, plans, directory) {
271
271
  mkdirSync(directory, { recursive: true, mode: 0o700 });
272
- const written = [];
273
- let added = 0;
274
- for (const [index, file] of files.entries()) {
275
- run.signal.throwIfAborted();
272
+ // Several pieces at once, in order (`piece-jobs.ts`).
273
+ const written = await mapPieces(run, files, async (file, index, own) => {
276
274
  const plan = plans[index];
277
275
  const output = join(directory, `paced-${String(index + 1).padStart(4, "0")}.wav`);
278
276
  await runFfmpeg({
279
- bin: run.bin,
277
+ bin: own.bin,
280
278
  args: insertArgs(file, output, plan?.pauses.inserts ?? [], plan?.padEnd ?? 0, {
281
279
  sampleRate: 44100,
282
280
  channels: 1,
283
281
  }),
284
- signal: run.signal,
285
- log: run.log,
282
+ signal: own.signal,
283
+ log: own.log,
286
284
  onProgress: () => { },
287
285
  });
288
- added += (plan?.pauses.inserts.length ?? 0) + ((plan?.padEnd ?? 0) > 0 ? 1 : 0);
289
- written.push(output);
290
- }
286
+ return output;
287
+ });
288
+ const added = files.reduce((sum, _file, index) => {
289
+ const plan = plans[index];
290
+ return sum + (plan?.pauses.inserts.length ?? 0) + ((plan?.padEnd ?? 0) > 0 ? 1 : 0);
291
+ }, 0);
291
292
  return { files: written, added };
292
293
  }
293
294
  function round(value) {
@@ -0,0 +1,54 @@
1
+ import { availableParallelism } from "node:os";
2
+ // The join's per-piece steps (levelling, each sentence, breaths, S sounds, pauses) are each one
3
+ // ffmpeg audio pass per piece, and an audio pass keeps about one core busy. One piece at a time
4
+ // left a 32-thread machine nearly idle for most of an hour on a 2.5-hour narration, so several
5
+ // pieces go at once. Measured on 32 threads, eight real 4.8-minute pieces through levelling,
6
+ // each sentence, breaths, S sounds and pauses: one at a time 87 s, three 34 s, six 24 s, eight
7
+ // 14 s (all eight in one go), twelve 15 s. A render or another project's run may want the
8
+ // machine as well, so six is the most, and four cores are counted for each.
9
+ export const mostPieceJobs = 6;
10
+ const coresPerPieceJob = 4;
11
+ export function pieceJobs(cores = availableParallelism()) {
12
+ return Math.max(1, Math.min(mostPieceJobs, Math.floor(cores / coresPerPieceJob)));
13
+ }
14
+ // `work` over every item, at most `run.jobs` (else `pieceJobs()`) at once, the results in the
15
+ // items' order. Each call is given a run of its own whose signal ends with the caller's, so
16
+ // cancelling the run stops what is going and nothing new starts. The first failure stops the
17
+ // rest the same way, and once every call has ended that failure is the one thrown, not the
18
+ // cancellations it caused.
19
+ export async function mapPieces(run, items, work) {
20
+ run.signal.throwIfAborted();
21
+ const stop = new AbortController();
22
+ const follow = () => {
23
+ stop.abort(run.signal.reason);
24
+ };
25
+ run.signal.addEventListener("abort", follow, { once: true });
26
+ const own = { ...run, signal: stop.signal };
27
+ const results = new Array(items.length);
28
+ let next = 0;
29
+ let failed;
30
+ const runner = async () => {
31
+ while (failed === undefined && !stop.signal.aborted && next < items.length) {
32
+ const at = next;
33
+ next += 1;
34
+ try {
35
+ results[at] = await work(items[at], at, own);
36
+ }
37
+ catch (error) {
38
+ failed ??= { error };
39
+ stop.abort(error);
40
+ }
41
+ }
42
+ };
43
+ const limit = Math.max(1, Math.min(run.jobs ?? pieceJobs(), items.length));
44
+ try {
45
+ await Promise.all(Array.from({ length: limit }, runner));
46
+ }
47
+ finally {
48
+ run.signal.removeEventListener("abort", follow);
49
+ }
50
+ if (failed !== undefined)
51
+ throw failed.error;
52
+ run.signal.throwIfAborted();
53
+ return results;
54
+ }
@@ -186,8 +186,51 @@ export function skippedSpeakerPronunciationsNotice(rows) {
186
186
  return (`Speaker pronunciations: some entries are skipped and read as ordinary text (${parts.join(". ")}). ` +
187
187
  `The rest are used. To use them, fix those entries under Speakers → Pronunciations for that speaker (${createRows.narration}, or ${editSettings.narration}).`);
188
188
  }
189
- // Remembered (`kernel/remembered.ts`): every plan rebuild matches the whole narration again.
190
- export const pronunciationMatches = remembered(1024, (source, entries, possessives) => `${possessives === true ? "p" : "-"}\u0000${source}\u0000${JSON.stringify(entries)}`, matchPronunciations);
189
+ // Remembered: every plan rebuild matches the whole narration again, chunk by chunk, and a plan
190
+ // is derived again after every finished step of a run. The answers are kept per glossary, then
191
+ // per text. A glossary is known by its contents, written out once per array it arrives in (the
192
+ // parsed glossary is itself remembered, so that is once per glossary): writing it out and
193
+ // gluing it to the narration on every call was most of the matching's cost.
194
+ const glossaryKeys = new WeakMap();
195
+ function glossaryKey(entries) {
196
+ const known = glossaryKeys.get(entries);
197
+ // The length too: an array is never changed once made, but one that grew is not the same.
198
+ if (known !== undefined && known.length === entries.length)
199
+ return known.key;
200
+ const key = JSON.stringify(entries);
201
+ glossaryKeys.set(entries, { length: entries.length, key });
202
+ return key;
203
+ }
204
+ // ceilings: glossaries kept at once (a run's projects, each with and without possessives), and
205
+ // texts kept per glossary (a narration's chunks and the whole of it, for a few projects).
206
+ const rememberedGlossaries = 16;
207
+ const rememberedTexts = 1024;
208
+ // A pure function of a text and a glossary, remembered per glossary and then per text.
209
+ function byGlossary(work) {
210
+ const byKey = new Map();
211
+ return (source, entries, possessives = false) => {
212
+ const glossary = `${possessives ? "p" : "-"}${glossaryKey(entries)}`;
213
+ let texts = byKey.get(glossary);
214
+ if (texts === undefined) {
215
+ texts = new Map();
216
+ byKey.set(glossary, texts);
217
+ if (byKey.size > rememberedGlossaries)
218
+ byKey.delete(byKey.keys().next().value);
219
+ }
220
+ if (texts.has(source)) {
221
+ const known = texts.get(source);
222
+ texts.delete(source);
223
+ texts.set(source, known);
224
+ return known;
225
+ }
226
+ const value = work(source, entries, possessives);
227
+ texts.set(source, value);
228
+ if (texts.size > rememberedTexts)
229
+ texts.delete(texts.keys().next().value);
230
+ return value;
231
+ };
232
+ }
233
+ export const pronunciationMatches = byGlossary(matchPronunciations);
191
234
  function matchPronunciations(source, entries, possessives = false) {
192
235
  if (entries.length === 0)
193
236
  return [];
@@ -236,7 +279,9 @@ function withPossessive(ipa) {
236
279
  return `${ipa}\u026az`;
237
280
  return `${ipa}${"ptkfθ".includes(last) ? "s" : "z"}`;
238
281
  }
239
- export function pronunciationSpans(source, entries, possessives = false) {
282
+ // Remembered like the matches: asked again for every chunk each time the plan is derived.
283
+ export const pronunciationSpans = byGlossary(spansOf);
284
+ function spansOf(source, entries, possessives) {
240
285
  const spans = [];
241
286
  for (const match of pronunciationMatches(source, entries, possessives)) {
242
287
  const words = Array.from(source.slice(match.start, match.end).matchAll(/\S+/gu));
@@ -61,7 +61,7 @@ export function admitPreview(deps, input) {
61
61
  for (const recipe of snapshot.recipes) {
62
62
  const disposition = snapshot.dispositions.find((row) => row.key === recipe.key)?.disposition;
63
63
  const existing = deps.db
64
- .prepare(`SELECT w.id,w.state,w.recipe_context,r.piece_id,r.fingerprint FROM revision_work_reservations r JOIN revision_work w ON w.id=r.work_id WHERE r.revision_id=? AND r.work_key=?`)
64
+ .prepare(`SELECT w.id,w.state,w.recipe_context,r.piece_id,r.fingerprint,r.logical_key FROM revision_work_reservations r JOIN revision_work w ON w.id=r.work_id WHERE r.revision_id=? AND r.work_key=?`)
65
65
  .get(view.revision.id, recipe.key);
66
66
  if (disposition === "reuse") {
67
67
  bindNarrationReuse(deps, view, recipe, snapshot.ordinals[recipe.key] ?? 0);
@@ -71,6 +71,19 @@ export function admitPreview(deps, input) {
71
71
  typeof existing.recipe_context === "string" &&
72
72
  existing.state !== "done") {
73
73
  workIds.push(String(existing.id));
74
+ // A step reserved under a key this version's plan doesn't list (a picture check
75
+ // admitted under its own key before it was held to its picture) was never the
76
+ // version's to run, so a restart left it held for good: it takes the starting point a
77
+ // new one would. One whose key is listed under another fingerprint stays held below.
78
+ const own = typeof existing.logical_key === "string" ? existing.logical_key : recipe.key;
79
+ const anchorKey = reservationKey(recipe, view);
80
+ const anchor = snapshot.anchors[anchorKey];
81
+ if (view.revision.fingerprints[own] === undefined &&
82
+ anchor !== undefined &&
83
+ view.revision.fingerprints[anchorKey] === anchor)
84
+ deps.db
85
+ .prepare("UPDATE revision_work_reservations SET logical_key=?,desired_fingerprint=? WHERE revision_id=? AND work_key=? AND work_id=?")
86
+ .run(anchorKey, anchor, view.revision.id, recipe.key, String(existing.id));
74
87
  if (existing.state !== "running") {
75
88
  deps.db
76
89
  .prepare("UPDATE revision_work SET state='pending',dispatch_state='allowed',failure_reason=NULL,failure_kind=NULL,retry_at=NULL,auto_retries=0 WHERE id=?")
@@ -2,34 +2,83 @@ import { statSync } from "node:fs";
2
2
  import { z } from "zod";
3
3
  import { assetPathOrUndefined } from "../revisions/mutation-assets.js";
4
4
  import { stagePieceSchema } from "../revisions/schema.js";
5
- import { outputPath } from "../storage/layout.js";
5
+ import { outputPath, outputPaths } from "../storage/layout.js";
6
+ const keptRecords = new WeakMap();
7
+ const keptProjects = 12;
8
+ const historyRow = z.object({
9
+ id: z.string(),
10
+ piece_key: z.string(),
11
+ asset_id: z.string(),
12
+ fingerprint: z.string(),
13
+ path: z.string(),
14
+ });
15
+ const descriptorRow = z.object({ id: z.string(), descriptor: z.string() });
16
+ // Forgets every narration record kept for this database (tests compare against fresh reads).
17
+ export function forgetNarrationHistory(db) {
18
+ keptRecords.delete(db);
19
+ }
6
20
  export function retainedNarrationPieces(deps, projectId) {
7
- return deps.db
8
- .prepare(`SELECT p.piece_key,p.asset_id,p.fingerprint,p.descriptor,a.path FROM revision_pieces p
21
+ return retainedNarrationHistory(deps, projectId).pieces;
22
+ }
23
+ // The same, and a mark of it for the plan's key: which saved rows it holds, and whether each
24
+ // one's file is on disk. Two histories with one mark hold the same pieces, since a saved
25
+ // record never changes.
26
+ export function retainedNarrationHistory(deps, projectId) {
27
+ const rows = deps.db
28
+ .prepare(`SELECT p.id,p.piece_key,p.asset_id,p.fingerprint,a.path FROM revision_pieces p
9
29
  JOIN project_assets a ON a.id=p.asset_id AND a.project_id=p.project_id
10
30
  WHERE p.project_id=? AND p.stage_kind='audio' ORDER BY p.created_at,p.id`)
11
31
  .all(projectId)
12
- .map((value) => {
13
- const row = z
14
- .object({
15
- piece_key: z.string(),
16
- asset_id: z.string(),
17
- fingerprint: z.string(),
18
- descriptor: z.string(),
19
- path: z.string(),
20
- })
21
- .parse(value);
22
- return {
23
- key: row.piece_key,
24
- stageKind: "audio",
25
- assetId: row.asset_id,
26
- fingerprint: row.fingerprint,
27
- piece: stagePieceSchema.parse(JSON.parse(row.descriptor)),
28
- available: statSync(outputPath(deps.paths, projectId, row.path), {
29
- throwIfNoEntry: false,
30
- })?.isFile() === true,
31
- };
32
+ .map((value) => historyRow.parse(value));
33
+ const forDb = keptRecords.get(deps.db) ?? new Map();
34
+ keptRecords.set(deps.db, forDb);
35
+ const before = forDb.get(projectId);
36
+ // The columns read with the rows must still match the kept record, or it is read again.
37
+ const keeps = (row, kept) => kept !== undefined &&
38
+ kept.key === row.piece_key &&
39
+ kept.assetId === row.asset_id &&
40
+ kept.fingerprint === row.fingerprint;
41
+ const missing = rows.filter((row) => !keeps(row, before?.get(row.id)));
42
+ const descriptors = new Map();
43
+ const one = deps.db.prepare("SELECT id,descriptor FROM revision_pieces WHERE id=?");
44
+ for (const row of missing) {
45
+ const found = one.get(row.id);
46
+ if (found !== undefined) {
47
+ const parsed = descriptorRow.parse(found);
48
+ descriptors.set(parsed.id, parsed.descriptor);
49
+ }
50
+ }
51
+ const records = new Map();
52
+ const marks = [];
53
+ const pathOf = outputPaths(deps.paths, projectId);
54
+ const result = rows.flatMap((row) => {
55
+ const kept = before?.get(row.id);
56
+ let record;
57
+ if (kept !== undefined && keeps(row, kept))
58
+ record = kept;
59
+ else {
60
+ const descriptor = descriptors.get(row.id);
61
+ // Deleted between the two reads: it is no longer part of the history.
62
+ if (descriptor === undefined)
63
+ return [];
64
+ record = {
65
+ key: row.piece_key,
66
+ stageKind: "audio",
67
+ assetId: row.asset_id,
68
+ fingerprint: row.fingerprint,
69
+ piece: stagePieceSchema.parse(JSON.parse(descriptor)),
70
+ };
71
+ }
72
+ records.set(row.id, record);
73
+ const available = statSync(pathOf(row.path), { throwIfNoEntry: false })?.isFile() === true;
74
+ marks.push(`${row.id}:${row.piece_key}:${row.asset_id}:${row.fingerprint}:${available ? 1 : 0}`);
75
+ return [{ ...record, available }];
32
76
  });
77
+ forDb.delete(projectId);
78
+ forDb.set(projectId, records);
79
+ if (forDb.size > keptProjects)
80
+ forDb.delete(forDb.keys().next().value);
81
+ return { pieces: result, mark: marks.join("\n") };
33
82
  }
34
83
  export function referencedAssetsAvailable(deps, projectId, ids) {
35
84
  return ids.filter((id) => {
@@ -1,5 +1,18 @@
1
1
  import { z } from "zod";
2
2
  import { fingerprint } from "../../kernel/runner/work.js";
3
+ // The request a narration piece was voiced for, read from its payload once per piece: the plan
4
+ // asks it of every retained piece for every narration step it derives.
5
+ const requests = new WeakMap();
6
+ const requestPayload = z.object({ requestFingerprint: z.string() });
7
+ function requestOf(piece) {
8
+ const known = requests.get(piece);
9
+ if (known !== undefined)
10
+ return known;
11
+ const parsed = requestPayload.safeParse(JSON.parse(piece.payload ?? "null"));
12
+ const request = parsed.success ? parsed.data.requestFingerprint : null;
13
+ requests.set(piece, request);
14
+ return request;
15
+ }
3
16
  export function matchingNarrationPiece(recipe, pieces, available) {
4
17
  if (recipe.input.kind !== "tts")
5
18
  return undefined;
@@ -10,11 +23,9 @@ export function matchingNarrationPiece(recipe, pieces, available) {
10
23
  piece.assetId === null ||
11
24
  !available.has(piece.assetId))
12
25
  return false;
13
- const parsed = z
14
- .object({ requestFingerprint: z.string() })
15
- .safeParse(JSON.parse(piece.piece.payload ?? "null"));
16
- return (parsed.success &&
17
- parsed.data.requestFingerprint === recipe.requestFingerprint &&
26
+ const request = requestOf(piece.piece);
27
+ return (request !== null &&
28
+ request === recipe.requestFingerprint &&
18
29
  (noRegeneration || piece.fingerprint === recipe.fingerprint));
19
30
  });
20
31
  }
@@ -12,12 +12,22 @@ export function providedDependencyFingerprint(plan, key) {
12
12
  : null,
13
13
  });
14
14
  }
15
- export function applyProvidedReviews(db, revisionId, plan) {
16
- const approved = new Set(db
15
+ export function providedReviews(db, revisionId) {
16
+ return db
17
17
  .prepare("SELECT work_key,dependency_fingerprint FROM revision_provided_reviews WHERE revision_id=?")
18
18
  .all(revisionId)
19
- .filter((row) => row.dependency_fingerprint === providedDependencyFingerprint(plan, String(row.work_key)))
20
- .map((row) => String(row.work_key)));
19
+ .map((row) => ({
20
+ workKey: String(row.work_key),
21
+ dependencyFingerprint: row.dependency_fingerprint,
22
+ }));
23
+ }
24
+ export function applyProvidedReviews(db, revisionId, plan) {
25
+ return applyReviews(providedReviews(db, revisionId), plan);
26
+ }
27
+ export function applyReviews(reviews, plan) {
28
+ const approved = new Set(reviews
29
+ .filter((row) => row.dependencyFingerprint === providedDependencyFingerprint(plan, row.workKey))
30
+ .map((row) => row.workKey));
21
31
  return {
22
32
  ...plan,
23
33
  work: plan.work.map((row) => approved.has(row.key) && row.disposition === "review"
@@ -1,6 +1,6 @@
1
1
  import { sourceOf, subjectOf } from "../admission/model.js";
2
2
  import { resolvedDocumentTheme } from "../document/theme.js";
3
- import { recipe, resourceIdentity, } from "./recipe-model.js";
3
+ import { recipe, settledRecipe, } from "./recipe-model.js";
4
4
  // Bumped when the renderer's output changes for the same inputs, so documents made by an
5
5
  // older one read as outdated rather than current.
6
6
  const renderer = "document-v1";
@@ -14,22 +14,28 @@ export function documentRecipes(context, text, thumbnail) {
14
14
  const notes = text.recipes.find((value) => value.key === "research:notes");
15
15
  const cover = thumbnail.find((value) => value.key === "thumbnail:image");
16
16
  const theme = resolvedDocumentTheme(config.document);
17
+ const inputs = [
18
+ text.article,
19
+ ...[notes, cover].flatMap((value) => (value === undefined ? [] : [value])),
20
+ ];
21
+ // The article and notes are several files each; their identity doesn't follow the order a
22
+ // version lists them in (`settledRecipe`).
17
23
  return [
18
- recipe(context, "document:pdf", "document", {
19
- kind: "local",
20
- version: 1,
21
- operation: "render-document",
22
- values: [
23
- renderer,
24
- subjectOf(config),
25
- JSON.parse(JSON.stringify(theme)),
26
- resourceIdentity(context, text.article),
27
- notes === undefined ? null : resourceIdentity(context, notes),
28
- cover === undefined ? null : resourceIdentity(context, cover),
29
- ],
30
- }, [
31
- text.article.key,
32
- ...[notes, cover].flatMap((value) => (value === undefined ? [] : [value.key])),
33
- ]),
24
+ settledRecipe(context, inputs, (identities) => {
25
+ const identity = (value) => value === undefined ? null : (identities[inputs.indexOf(value)] ?? null);
26
+ return recipe(context, "document:pdf", "document", {
27
+ kind: "local",
28
+ version: 1,
29
+ operation: "render-document",
30
+ values: [
31
+ renderer,
32
+ subjectOf(config),
33
+ JSON.parse(JSON.stringify(theme)),
34
+ identity(text.article),
35
+ identity(notes),
36
+ identity(cover),
37
+ ],
38
+ }, inputs.map((value) => value.key));
39
+ }),
34
40
  ];
35
41
  }
@@ -64,7 +64,14 @@ unsoftened = () => []) {
64
64
  row.fingerprint === fingerprint &&
65
65
  (row.state === "ready" || row.state === "outdated")));
66
66
  };
67
- const timing = timedNow === undefined || doneTiming(timedNow.fingerprint)
67
+ // The softening variants plan the whole narration again each, on every plan rebuild: look for
68
+ // one only when the project has a finished timing at all.
69
+ const anyDoneTiming = () => {
70
+ const past = context.history ?? context.manifest;
71
+ return (past.pieces.some((row) => row.key === "subtitles:timing" && row.piece.state === "done") ||
72
+ past.outputs.some((row) => row.workKey === "subtitles:timing" && (row.state === "ready" || row.state === "outdated")));
73
+ };
74
+ const timing = timedNow === undefined || doneTiming(timedNow.fingerprint) || !anyDoneTiming()
68
75
  ? timedNow
69
76
  : (unsoftened()
70
77
  .map(timingOf)
@@ -1,5 +1,4 @@
1
- import { z } from "zod";
2
- import { fingerprint } from "../../kernel/runner/work.js";
1
+ import { fingerprint, fingerprintJson } from "../../kernel/runner/work.js";
3
2
  import { narrationRegenerationToken, narrationRequestFingerprint } from "../narration/plan.js";
4
3
  export const localOperations = [
5
4
  "export-wav",
@@ -71,7 +70,8 @@ export function recipe(context, key, stage, input, dependsOn = [], options = {})
71
70
  ...input,
72
71
  wholeText: input.wholeRequest === true ? input.logicalText : null,
73
72
  })
74
- : fingerprint(JSON.parse(JSON.stringify(input, (_key, value) => typeof value === "number" ? z.number().finite().parse(value) : value)));
73
+ : // As JSON writes the input, every number finite (`kernel/runner/work.ts`).
74
+ fingerprintJson(input);
75
75
  const token = input.kind === "tts"
76
76
  ? narrationRegenerationToken(context.content.regenerationTokens, input.logicalKey, input.segment)
77
77
  : options.token !== undefined
@@ -103,7 +103,7 @@ export function recipe(context, key, stage, input, dependsOn = [], options = {})
103
103
  };
104
104
  }
105
105
  export function selectedAsset(context, key, desired) {
106
- const output = context.manifest.outputs.find((row) => row.workKey === key && row.state === "ready" && selectedReference(row));
106
+ const output = readyFiles(context, key)[0];
107
107
  if (output !== undefined)
108
108
  return output.assetId;
109
109
  const piece = context.manifest.pieces.find((row) => row.key === key &&
@@ -115,6 +115,50 @@ export function selectedAsset(context, key, desired) {
115
115
  export function resourceIdentity(context, value) {
116
116
  return [value.fingerprint, selectedAsset(context, value.key, value.fingerprint)];
117
117
  }
118
+ // A step that writes several files (the article: its text, plain text, sources and glossary)
119
+ // has one ready output per slot, and the manifest lists them in the order the version's rows
120
+ // were saved in, which every save draws afresh with new row ids. The files sorted by slot, so
121
+ // the one that stands for the step in `resourceIdentity` is the same on every version that
122
+ // keeps them; a step with one file is unchanged.
123
+ function readyFiles(context, key) {
124
+ return context.manifest.outputs
125
+ .filter((row) => row.workKey === key && row.state === "ready" && selectedReference(row))
126
+ .toSorted((a, b) => (a.slot < b.slot ? -1 : a.slot > b.slot ? 1 : 0));
127
+ }
128
+ // Each identity `resourceIdentity` may have given this input before it sorted the files: the
129
+ // fixed one first, then one per other file of the step. Only for `settledRecipe`.
130
+ function resourceIdentities(context, value) {
131
+ const fixed = resourceIdentity(context, value);
132
+ const others = [...new Set(readyFiles(context, value.key).map((row) => row.assetId))].filter((assetId) => assetId !== selectedAsset(context, value.key, value.fingerprint));
133
+ return [fixed, ...others.map((assetId) => [value.fingerprint, assetId])];
134
+ }
135
+ // ceiling: the variants one step is planned in; the article's four files are four.
136
+ const variantLimit = 32;
137
+ // One step planned with each identity its inputs may have had (`variant` gets one identity per
138
+ // input, by place, the fixed choice first): the variant a finished piece or ready output of this
139
+ // version was made with, so a step Slopify finished while another of a step's files happened to
140
+ // be listed first is kept rather than made and paid for again; otherwise the fixed choice.
141
+ export function settledRecipe(context, inputs, variant) {
142
+ const choices = inputs.map((input) => resourceIdentities(context, input));
143
+ const fixed = variant(choices.map((one) => one[0] ?? null));
144
+ if (choices.every((one) => one.length <= 1))
145
+ return fixed;
146
+ const finished = (row) => context.manifest.pieces.some((one) => one.key === row.key && one.piece.state === "done" && one.fingerprint === row.fingerprint) ||
147
+ context.manifest.outputs.some((one) => one.workKey === row.key && one.state === "ready" && one.fingerprint === row.fingerprint);
148
+ if (finished(fixed))
149
+ return fixed;
150
+ let combos = [[]];
151
+ for (const one of choices)
152
+ combos = combos
153
+ .flatMap((picked) => one.map((identity) => [...picked, identity]))
154
+ .slice(0, variantLimit);
155
+ for (const combo of combos.slice(1)) {
156
+ const row = variant(combo);
157
+ if (finished(row))
158
+ return row;
159
+ }
160
+ return fixed;
161
+ }
118
162
  export function selectedReference(value) {
119
163
  return !("selected" in value) || value.selected === true;
120
164
  }
@@ -55,18 +55,40 @@ export function preparationForGroup(context, logicalKey, source, segment, depend
55
55
  .safeParse(JSON.parse(row.piece.payload ?? "null")).success)));
56
56
  if (saved?.piece.payload === undefined || saved.piece.payload === null)
57
57
  return { preparation, requests: null, refusal: null };
58
- const payload = z.object({ text: z.string() }).safeParse(JSON.parse(saved.piece.payload));
58
+ return {
59
+ preparation,
60
+ ...savedRequests(saved.piece.payload, source, context.catalogue === undefined ? null : maxCharacters, spans),
61
+ };
62
+ }
63
+ const rememberedAnswers = 1024;
64
+ const savedAnswers = new Map();
65
+ function savedRequests(answer, source, maxCharacters, spans) {
66
+ const key = JSON.stringify([answer, source, maxCharacters, spans]);
67
+ const known = savedAnswers.get(key);
68
+ if (known !== undefined) {
69
+ savedAnswers.delete(key);
70
+ savedAnswers.set(key, known);
71
+ return known;
72
+ }
73
+ const value = prepareSaved(answer, source, maxCharacters, spans);
74
+ savedAnswers.set(key, value);
75
+ if (savedAnswers.size > rememberedAnswers)
76
+ savedAnswers.delete(savedAnswers.keys().next().value);
77
+ return value;
78
+ }
79
+ function prepareSaved(answer, source, maxCharacters, spans) {
80
+ const payload = z.object({ text: z.string() }).safeParse(JSON.parse(answer));
59
81
  if (!payload.success)
60
- return { preparation, requests: null, refusal: "Saved narration preparation is incomplete." };
82
+ return { requests: null, refusal: "Saved narration preparation is incomplete." };
61
83
  const validated = validatePreparation(payload.data.text, source);
62
84
  if (!validated.ok)
63
- return { preparation, requests: null, refusal: validated.reason };
64
- const prepared = prepareRequests(source, validated.cues, context.catalogue === undefined
85
+ return { requests: null, refusal: validated.reason };
86
+ const prepared = prepareRequests(source, validated.cues, maxCharacters === null
65
87
  ? Math.max(2, source.length +
66
88
  spans.reduce((sum, span) => sum + Math.max(0, span.text.length - (span.end - span.start)), 0) +
67
89
  validated.cues.reduce((n, cue) => n + (cue.kind === "instruction" ? cue.text.length : 20) + 3, 0))
68
90
  : maxCharacters, spans);
69
91
  return prepared.ok
70
- ? { preparation, requests: prepared.requests, refusal: null }
71
- : { preparation, requests: null, refusal: prepared.reason };
92
+ ? { requests: prepared.requests, refusal: null }
93
+ : { requests: null, refusal: prepared.reason };
72
94
  }