@gentbajko/slopify 4.5.1 → 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 (54) hide show
  1. package/dist/edge/mcp/tools-runs.js +1 -1
  2. package/dist/extension/slopify-studio-chrome.zip +0 -0
  3. package/dist/extension/slopify-studio-firefox.zip +0 -0
  4. package/dist/kernel/db/migrations/0079-plan-history-indexes.sql +11 -0
  5. package/dist/kernel/db/migrations/0080-attempts-work-index.sql +4 -0
  6. package/dist/kernel/runner/providers.js +1 -1
  7. package/dist/kernel/runner/queue.js +31 -5
  8. package/dist/kernel/runner/work.js +52 -1
  9. package/dist/main.js +1 -1
  10. package/dist/patch-notes/4.5.2.md +17 -0
  11. package/dist/patch-notes/4.5.3.md +16 -0
  12. package/dist/patch-notes/index.json +12 -0
  13. package/dist/slices/article/production-note.js +75 -0
  14. package/dist/slices/loudness/level-pieces.js +12 -8
  15. package/dist/slices/loudness/sentence-level.js +35 -24
  16. package/dist/slices/narration/breaths-worker.js +126 -0
  17. package/dist/slices/narration/breaths.js +19 -81
  18. package/dist/slices/narration/clean-pieces.js +9 -10
  19. package/dist/slices/narration/pauses.js +18 -17
  20. package/dist/slices/narration/piece-jobs.js +54 -0
  21. package/dist/slices/narration/pronunciation.js +48 -3
  22. package/dist/slices/rebuild/admission-repo.js +14 -1
  23. package/dist/slices/rebuild/narration-history.js +72 -23
  24. package/dist/slices/rebuild/narration-reuse.js +16 -5
  25. package/dist/slices/rebuild/provided-review.js +14 -4
  26. package/dist/slices/rebuild/recipe-audio.js +6 -0
  27. package/dist/slices/rebuild/recipe-build.js +6 -2
  28. package/dist/slices/rebuild/recipe-document.js +23 -17
  29. package/dist/slices/rebuild/recipe-exports.js +8 -1
  30. package/dist/slices/rebuild/recipe-model.js +48 -4
  31. package/dist/slices/rebuild/recipe-preparation.js +28 -6
  32. package/dist/slices/rebuild/recipe-reviews.js +28 -24
  33. package/dist/slices/rebuild/recipe-save.js +16 -3
  34. package/dist/slices/rebuild/recipe-shorts.js +195 -8
  35. package/dist/slices/rebuild/recovery.js +35 -2
  36. package/dist/slices/rebuild/review-redo.js +15 -7
  37. package/dist/slices/rebuild/runtime-admission.js +5 -0
  38. package/dist/slices/rebuild/runtime-agent-review.js +4 -2
  39. package/dist/slices/rebuild/runtime-materialize.js +14 -0
  40. package/dist/slices/rebuild/runtime-plan.js +86 -40
  41. package/dist/slices/rebuild/runtime-provider.js +11 -4
  42. package/dist/slices/rebuild/runtime-review.js +3 -2
  43. package/dist/slices/rebuild/runtime-shorts.js +53 -13
  44. package/dist/slices/rebuild/transition-repo.js +13 -10
  45. package/dist/slices/reviews/outcome.js +5 -3
  46. package/dist/slices/reviews/repo.js +12 -0
  47. package/dist/slices/revisions/schema.js +1 -0
  48. package/dist/slices/revisions/view.js +3 -3
  49. package/dist/slices/settings/model.js +6 -2
  50. package/dist/slices/shorts/keep.js +37 -17
  51. package/dist/slices/storage/layout.js +15 -0
  52. package/dist/web/assets/{index-C0n0zeuZ.js → index-C8aMp7m3.js} +2 -2
  53. package/dist/web/index.html +1 -1
  54. package/package.json +1 -1
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  import { narrationItemKey, promiseItemKey, reviewedByAgent, reviewKey, reviewModeOf, reviewPromptKey, reviewRetriesOf, } from "../reviews/model.js";
2
2
  import { activeReviewStages } from "../reviews/rules.js";
3
- import { recipe, resourceIdentity, } from "./recipe-model.js";
3
+ import { recipe, settledRecipe, } from "./recipe-model.js";
4
4
  import { promptOf } from "./recipe-text.js";
5
5
  // A review is a step of its own, `review:<item>`, planned like any other: it waits for the
6
6
  // item, its fingerprint follows the item's output, the reviewer and the prompt, and it is
@@ -20,7 +20,6 @@ export function withReviews(context, recipes) {
20
20
  : all.filter((item, index) => all.findIndex((one) => one.stage === item.stage) === index);
21
21
  const byAgent = reviewedByAgent(settings);
22
22
  const reviews = items.map((item) => {
23
- const inputs = item.inputs.map((input) => [input.key, resourceIdentity(context, input)]);
24
23
  // Blank means the stage's built-in prompt; the step fills it in, so a new built-in
25
24
  // wording ships as a new operation version rather than a silent change here.
26
25
  const filled = settings.stages[item.stage]?.prompt?.trim()
@@ -30,39 +29,44 @@ export function withReviews(context, recipes) {
30
29
  const dependsOn = [
31
30
  ...new Set([...item.inputs.map((input) => input.key), ...(filled?.dependsOn ?? [])]),
32
31
  ];
33
- // An external agent answers through MCP: no provider, no charge, nothing to be ready.
34
- if (byAgent)
32
+ // The item's files by identity, the same whatever order a version lists them in
33
+ // (`settledRecipe`): a picture drawn again doesn't send the article back to its reviewer.
34
+ return settledRecipe(context, item.inputs, (identities) => {
35
+ const inputs = item.inputs.map((input, index) => [input.key, identities[index] ?? null]);
36
+ // An external agent answers through MCP: no provider, no charge, nothing to be ready.
37
+ if (byAgent)
38
+ return recipe(context, reviewKey(item.itemKey), stageOf(item.stage), {
39
+ kind: "local",
40
+ version: 1,
41
+ operation: "review-agent-v1",
42
+ values: [
43
+ item.stage,
44
+ item.itemKey,
45
+ inputs,
46
+ prompt,
47
+ reviewModeOf(settings, item.stage),
48
+ reviewRetriesOf(settings),
49
+ ],
50
+ }, dependsOn);
35
51
  return recipe(context, reviewKey(item.itemKey), stageOf(item.stage), {
36
52
  kind: "local",
37
53
  version: 1,
38
- operation: "review-agent-v1",
54
+ operation: "review-v1",
39
55
  values: [
40
56
  item.stage,
41
57
  item.itemKey,
42
58
  inputs,
59
+ settings.provider,
60
+ settings.model,
61
+ settings.thinking ?? null,
43
62
  prompt,
44
63
  reviewModeOf(settings, item.stage),
45
64
  reviewRetriesOf(settings),
46
65
  ],
47
- }, dependsOn);
48
- return recipe(context, reviewKey(item.itemKey), stageOf(item.stage), {
49
- kind: "local",
50
- version: 1,
51
- operation: "review-v1",
52
- values: [
53
- item.stage,
54
- item.itemKey,
55
- inputs,
56
- settings.provider,
57
- settings.model,
58
- settings.thinking ?? null,
59
- prompt,
60
- reviewModeOf(settings, item.stage),
61
- reviewRetriesOf(settings),
62
- ],
63
- }, dependsOn,
64
- // A paid LLM call: readiness, the charge warning and the estimate treat it like one.
65
- { kind: "provider" });
66
+ }, dependsOn,
67
+ // A paid LLM call: readiness, the charge warning and the estimate treat it like one.
68
+ { kind: "provider" });
69
+ });
66
70
  });
67
71
  const gated = recipes.map((row) => {
68
72
  const waits = items.flatMap((item, index) => {
@@ -95,20 +95,33 @@ export function planRevision(base, edit, prepared = { outputs: [], pieces: [] },
95
95
  },
96
96
  ],
97
97
  };
98
+ // A keep list only says which finished shorts outlast a new pick. An edit that picks
99
+ // nothing again (a new intro or outro, a prompt, a picture) keeps every short as it is,
100
+ // whatever list it sent: one sent with nothing ticked must not drop them all.
101
+ const { shortsKeep: _chosen, ...rest } = edit.content;
102
+ const kept = base.revision.content.shortsKeep;
103
+ const unchosen = planEdit(base, { ...edit, content: kept === undefined ? rest : { ...rest, shortsKeep: kept } }, prepared, inspected, false);
104
+ if (unchosen.ok && !picksAgain(base, unchosen))
105
+ return unchosen;
98
106
  return planEdit(base, edit, prepared, inspected, true);
99
107
  }
100
108
  const first = planEdit(base, edit, prepared, inspected, false);
101
109
  if (!first.ok)
102
110
  return first;
103
- const before = base.pieces.find((row) => row.key === shortsPickKey && row.selected && row.piece.state === "done")?.fingerprint;
104
- const after = first.fingerprints[shortsPickKey];
105
- if (before === undefined || after === undefined || after === before)
111
+ if (!picksAgain(base, first))
106
112
  return first;
107
113
  const finished = finishedShorts(base);
108
114
  if (finished.length === 0)
109
115
  return first;
110
116
  return planEdit(base, { ...edit, content: { ...edit.content, shortsKeep: finished } }, prepared, inspected, true);
111
117
  }
118
+ // Whether a save's plan picks the moments again: its pick is another than the version's
119
+ // finished one. Without a finished pick there is nothing to keep.
120
+ function picksAgain(base, plan) {
121
+ const before = base.pieces.find((row) => row.key === shortsPickKey && row.selected && row.piece.state === "done")?.fingerprint;
122
+ const after = plan.fingerprints[shortsPickKey];
123
+ return before !== undefined && after !== undefined && after !== before;
124
+ }
112
125
  function planEdit(base, edit, prepared, inspected, keeping) {
113
126
  const normal = normalizeImages(normalizeArticleIntent(base, edit));
114
127
  // A keep list chosen in this save: kept shorts numbered by their place, their work moved
@@ -3,10 +3,14 @@ import { fingerprint } from "../../kernel/runner/work.js";
3
3
  import { subjectOf } from "../admission/model.js";
4
4
  import { usesShorts } from "../admission/rules.js";
5
5
  import { withoutScene } from "../images/scenes.js";
6
+ import { pausesOf } from "../narration/pauses-model.js";
7
+ import { narrationRegenerationToken } from "../narration/plan.js";
6
8
  import { effectiveClips, pickedShortsOf } from "../shorts/clips.js";
7
9
  import { defaultShortsImagePrompt, musicVolumeOf, shortImageCount, shortsSpeedOf, } from "../shorts/model.js";
8
10
  import { imagePromptMessages } from "../shorts/prompts.js";
9
11
  import { lookWait, withLooks } from "./recipe-appearance.js";
12
+ import { voiceValues } from "./recipe-audio-parts.js";
13
+ import { breathValues } from "./recipe-breaths.js";
10
14
  import { castFor } from "./recipe-cast.js";
11
15
  import { noMaster } from "./recipe-loudness.js";
12
16
  import { recipe, resourceIdentity, selectedAsset, selectedReference, } from "./recipe-model.js";
@@ -23,8 +27,17 @@ import { llmInput, promptOf } from "./recipe-text.js";
23
27
  // clip was first picked, plus the one "Make this short again" renews under `shorts:N`. So
24
28
  // picking the moments again redoes only the clips whose sentences changed, and one short
25
29
  // can be made again alone.
30
+ //
31
+ // Shorts are cut from the body only, on the body's own clock (`bodyTiming`): the pick reads
32
+ // the body's words with times from the body's start, and its fingerprint holds the body's
33
+ // narration and timing, not the intro's or outro's. A new intro or outro moves every word of
34
+ // the video's timing, yet leaves the pick, each clip's prompts and images, and its render as
35
+ // they are; the render finds the body where it now starts. A pick saved before this, on the
36
+ // video's clock, is kept while the timing it read is unchanged (`legacy` below).
26
37
  export const shortsPickKey = "shorts:pick";
27
38
  export const shortsFutureKey = "shorts:future";
39
+ // The first value of a pick and a render on the body's clock.
40
+ export const bodyClockValue = "body-clock-v1";
28
41
  export function shortsRecipes(context, exports,
29
42
  // The establishing image the shorts' images are drawn from, when it is on.
30
43
  reference,
@@ -33,7 +46,10 @@ cards = [],
33
46
  // Level the volume: the levelled narration and the master (`recipe-loudness.ts`).
34
47
  master = noMaster,
35
48
  // How the figures look, for a shorts image prompt with `{{Appearance}}` (`recipe-appearance.ts`).
36
- appearance) {
49
+ appearance,
50
+ // The body alone, what a short on the body's clock is cut from: its levelled sound and, when
51
+ // it is voiced chunk by chunk, its chunks.
52
+ narration = { master }) {
37
53
  const { config } = context;
38
54
  const shorts = config.shorts;
39
55
  const timing = exports.find((value) => value.key === "subtitles:timing");
@@ -78,6 +94,8 @@ appearance) {
78
94
  [...short.hashtags],
79
95
  short.why,
80
96
  short.seed ?? null,
97
+ // Only on lists that remember every word, so older lists keep theirs.
98
+ ...(short.text === undefined ? [] : [short.text]),
81
99
  ]),
82
100
  ],
83
101
  ]),
@@ -85,7 +103,8 @@ appearance) {
85
103
  }, [...new Set([timing.key, ...(prompt?.dependsOn ?? []), ...(styled?.dependsOn ?? [])])],
86
104
  // A paid LLM call: readiness, the charge warning and the estimate treat it like one.
87
105
  { kind: "provider" });
88
- const pick = pickFor(resourceIdentity(context, timing));
106
+ // A pick saved on the video's clock, asked of the whole timing: kept while it still matches.
107
+ const legacy = pickFor(resourceIdentity(context, timing));
89
108
  // The same pick asked of the finished timing as it was recorded: a run's plan reads the
90
109
  // catalogue, which gives the timing another fingerprint than the one the version was saved
91
110
  // with, while the timing file is the same.
@@ -95,7 +114,17 @@ appearance) {
95
114
  asset !== null &&
96
115
  row.fingerprint !== timing.fingerprint &&
97
116
  selectedReference(row));
98
- const picked = savedPicked(context, pick, recorded === undefined ? [] : [pickFor([recorded.fingerprint, asset]).fingerprint]);
117
+ const legacyPicked = savedPicked(context, legacy, recorded === undefined ? [] : [pickFor([recorded.fingerprint, asset]).fingerprint]);
118
+ const chunks = narration.chunks === undefined ? undefined : chunkSource(context, narration);
119
+ const body = bodyTiming(timing, chunks?.anchor);
120
+ const onBody = legacyPicked === undefined && body !== undefined;
121
+ const pick = onBody ? pickFor(body) : legacy;
122
+ const picked = onBody ? savedPicked(context, pick) : legacyPicked;
123
+ // What a render on each clock reads the narration by: the body's timing and its levelled
124
+ // sound, or the whole timing and every levelled part.
125
+ const heard = (clip) => onBody
126
+ ? (chunks?.span(clip, body) ?? { timing: body, master: narration.master })
127
+ : { timing: resourceIdentity(context, timing), master };
99
128
  const images = config.images ?? { provider: "", model: "" };
100
129
  const style = styled === undefined ? defaultShortsImagePrompt : withoutScene(styled.text);
101
130
  if (picked === undefined)
@@ -167,15 +196,17 @@ appearance) {
167
196
  }, [prompts.key, ...(reference === undefined ? [] : [reference.key])], { token }));
168
197
  recipes.push(...stills);
169
198
  const extras = renderExtras(context, clip);
199
+ const sound = heard(clip);
170
200
  recipes.push(recipe(context, `${prefix}:render`, "video", {
171
201
  kind: "local",
172
202
  version: 1,
173
203
  operation: "short-render-v1",
174
204
  values: [
175
- resourceIdentity(context, timing),
205
+ sound.timing,
176
206
  clip.number,
177
- clip.start,
178
- clip.end,
207
+ // On its chunks, a clip is placed by its words when it renders: where the body's
208
+ // other chunks moved it is no reason to cut it again.
209
+ ...("chunks" in sound ? [clip.text] : [clip.start, clip.end]),
179
210
  stills.map((still) => resourceIdentity(context, still)),
180
211
  config.imageSeconds,
181
212
  config.zoomPercent,
@@ -189,17 +220,173 @@ appearance) {
189
220
  ? []
190
221
  : [["figure-cards-v1", cards.map((card) => resourceIdentity(context, card))]]),
191
222
  // Only while the volume is levelled, so every short without it keeps its fingerprint.
192
- ...master.values,
223
+ ...sound.master.values,
193
224
  ],
194
225
  }, [
195
226
  pick.key,
196
227
  ...stills.map((still) => still.key),
197
228
  ...cards.map((card) => card.key),
198
- ...master.keys,
229
+ ...sound.master.keys,
199
230
  ], { token }));
200
231
  }
201
232
  return recipes;
202
233
  }
234
+ // What the shorts' pick reads on the body's clock: the body's narration as the word timing was
235
+ // made from it (its file once it is made, else its recipe, with what it says), and how the
236
+ // words are timed. Not the intro or outro, the silence between them or at the edges: those
237
+ // move the body's words on the video's clock and not on its own. Undefined when the timing
238
+ // has no body to find.
239
+ export function bodyTiming(timing,
240
+ // The body's chunks as they were voiced, in place of the body's file (`chunkSource`).
241
+ chunks) {
242
+ if (timing.input.kind !== "local" || !Array.isArray(timing.input.values))
243
+ return undefined;
244
+ const values = timing.input.values;
245
+ const [timeline, , language, , ...words] = values;
246
+ const at = timing.dependsOn.findIndex((key) => key !== "audio:intro" && key !== "audio:outro");
247
+ if (!Array.isArray(timeline) || at < 0)
248
+ return undefined;
249
+ const entries = timeline;
250
+ const entry = entries[at];
251
+ if (!isRecord(entry))
252
+ return undefined;
253
+ const audio = entry.audio;
254
+ const file = Array.isArray(audio) && typeof audio[1] === "string" ? audio[1] : undefined;
255
+ return [
256
+ bodyClockValue,
257
+ timing.input.operation,
258
+ chunks ?? (file === undefined ? entry : ["file", file, entry.transcript ?? null]),
259
+ language ?? null,
260
+ ...words,
261
+ ];
262
+ }
263
+ // A body voiced chunk by chunk. The pick reads the chunks' words and how they were asked for
264
+ // (`anchor`): a chunk's own regeneration, the voice, the pauses. Not their files, which land
265
+ // mid-run; a change that brings a new file is in the request. Each short is cut from the chunks
266
+ // its sentences fall in (`span`), so a chunk voiced again elsewhere, or words added before it,
267
+ // leave it as it is. A clip whose words can't be found once among the chunks reads all of them.
268
+ function chunkSource(context, narration) {
269
+ const list = narration.chunks ?? [];
270
+ const tokens = context.content.regenerationTokens;
271
+ const token = (key) => narrationRegenerationToken(tokens, key, "body");
272
+ const asked = [voiceValues(context), pausesValue(context)];
273
+ const anchor = [
274
+ "chunks-v1",
275
+ list.map((chunk) => [chunk.text, token(chunk.key)]),
276
+ ...asked,
277
+ ];
278
+ // What the body was voiced from, in order: each chunk's requests as they were made (a chunk
279
+ // longer than the voice takes in one request is several), with the words each said and its
280
+ // file; a chunk not voiced yet is itself one. Read from the version's records, not the plan,
281
+ // so a plan that splits a chunk otherwise reads the same files.
282
+ const units = list.flatMap((chunk) => {
283
+ const parts = context.manifest.pieces
284
+ .flatMap((row) => {
285
+ const number = row.key.startsWith(`${chunk.key}:`)
286
+ ? Number(row.key.slice(chunk.key.length + 1))
287
+ : Number.NaN;
288
+ if (!Number.isInteger(number) ||
289
+ row.piece.state !== "done" ||
290
+ !selectedReference(row) ||
291
+ row.assetId === null)
292
+ return [];
293
+ const text = partText(row.piece.payload);
294
+ return text === undefined ? [] : [{ number, text, file: row.assetId }];
295
+ })
296
+ .toSorted((left, right) => left.number - right.number);
297
+ const whole = parts.length > 0 && parts.every((part, at) => part.number === at + 1);
298
+ return whole
299
+ ? parts.map((part) => ({
300
+ text: part.text,
301
+ identity: [part.text, token(chunk.key), part.file],
302
+ }))
303
+ : [{ text: chunk.text, identity: [chunk.text, token(chunk.key), null] }];
304
+ });
305
+ // Their words run together, letters and digits only, with where each one ends.
306
+ let stream = "";
307
+ const ends = [];
308
+ for (const unit of units) {
309
+ stream += spokenLetters(unit.text);
310
+ ends.push(stream.length);
311
+ }
312
+ const level = narration.level?.input.kind === "local" && Array.isArray(narration.level.input.values)
313
+ ? narration.level.input.values.slice(2)
314
+ : [];
315
+ // The levelled body's master, with the body's own levelled file left out: how it is levelled.
316
+ const master = {
317
+ keys: narration.master.keys,
318
+ values: narration.master.values.map((value) => Array.isArray(value) && value[0] === "loudness-v1"
319
+ ? ["span-loudness-v1", level, ...value.slice(2)]
320
+ : value),
321
+ };
322
+ return {
323
+ anchor,
324
+ span: (clip, body) => {
325
+ const words = spokenLetters(clip.text);
326
+ const at = words === "" ? -1 : stream.indexOf(words);
327
+ if (at < 0 || stream.indexOf(words, at + 1) >= 0)
328
+ return undefined;
329
+ const first = ends.findIndex((end) => end > at);
330
+ const last = ends.findIndex((end) => end >= at + words.length);
331
+ if (first < 0 || last < 0)
332
+ return undefined;
333
+ const values = Array.isArray(body) ? body : [];
334
+ return {
335
+ chunks: true,
336
+ timing: [
337
+ bodyClockValue,
338
+ "span-v1",
339
+ // How the words are timed: the timing operation, language and voices marker.
340
+ values[1] ?? null,
341
+ values[3] ?? null,
342
+ ...values.slice(4),
343
+ units.slice(first, last + 1).map((unit) => unit.identity),
344
+ ...asked,
345
+ breathValues(context.config),
346
+ ],
347
+ master,
348
+ };
349
+ },
350
+ };
351
+ }
352
+ // The words a narration request was voiced from, as its piece saved them.
353
+ function partText(payload) {
354
+ if (payload === null)
355
+ return undefined;
356
+ try {
357
+ const parsed = JSON.parse(payload);
358
+ return typeof parsed === "object" &&
359
+ parsed !== null &&
360
+ "text" in parsed &&
361
+ typeof parsed.text === "string"
362
+ ? parsed.text
363
+ : undefined;
364
+ }
365
+ catch {
366
+ return undefined;
367
+ }
368
+ }
369
+ function pausesValue(context) {
370
+ const pauses = pausesOf(context.config);
371
+ return pauses === undefined ? null : [pauses.sentenceSeconds, pauses.paragraphSeconds];
372
+ }
373
+ // What a text says, as letters and digits only and without its delivery notes in brackets:
374
+ // how a clip's words are found in its chunks whatever the word timing made of the
375
+ // punctuation, case and spacing.
376
+ export function spokenLetters(text) {
377
+ return text
378
+ .replace(/\[[^\]]*\]/g, " ")
379
+ .normalize("NFKD")
380
+ .toLowerCase()
381
+ .replace(/[^\p{L}\p{N}]+/gu, "");
382
+ }
383
+ function isRecord(value) {
384
+ return typeof value === "object" && value !== null && !Array.isArray(value);
385
+ }
386
+ // Whether a pick's or a render's values are on the body's clock.
387
+ export function onBodyClock(values) {
388
+ return Array.isArray(values) && Array.isArray(values[0]) && values[0][0] === bodyClockValue;
389
+ }
203
390
  // What the render draws and plays beyond the clip itself: the title headline, a faster
204
391
  // speed and the background music at its level. Undefined when none is in use.
205
392
  export function renderExtras(context, clip) {
@@ -15,7 +15,7 @@ import { readRecovery, recoveryAuthority, recoveryKey, rememberRecovery, reserve
15
15
  import { dependentClosure, recoverySelection, redoTarget, regenerationEdit, resumeSelection, sectionRoots, } from "./recovery-selection.js";
16
16
  import { previewById, storePreview } from "./repo.js";
17
17
  import { admitCheckedPreview, wakeRebuild } from "./service.js";
18
- import { checkReadiness } from "./service-readiness.js";
18
+ import { checkReadiness, paidChoices } from "./service-readiness.js";
19
19
  function credentialsStamp(deps, plan, view) {
20
20
  const providers = new Set(plan.execution.recipes.flatMap((recipe) => {
21
21
  if (!plan.execution.submissions.some((row) => row.key === recipe.key && row.submit))
@@ -29,6 +29,29 @@ function credentialsStamp(deps, plan, view) {
29
29
  .filter((row) => providers.has(String(row.provider)));
30
30
  return requestHash("recovery-credentials", view.revision.id, metadata);
31
31
  }
32
+ // The same selection planned again on the same version, stored for admission, or undefined
33
+ // when the new plan asks for a service or model the readiness check did not cover, or would
34
+ // stop where the first plan's checks would have refused.
35
+ function replanCovered(deps, first, checked) {
36
+ // Read again: the outputs of the steps that finished meanwhile are what changed.
37
+ const view = getRevisionView(deps, checked.revision.projectId, checked.revision.id);
38
+ if (view === undefined)
39
+ return undefined;
40
+ const again = planPreview(deps, view, deps.catalogue.read(), first.preview.selection, deps.ids.next());
41
+ if (!again.ok)
42
+ return undefined;
43
+ const { preview, execution } = again.value;
44
+ if (preview.providedReuseRequired.length > 0 ||
45
+ preview.work.some((row) => row.disposition === "blocked"))
46
+ return undefined;
47
+ const choice = (row) => JSON.stringify([row.family, row.provider, row.model, row.voice ?? null, row.thinking ?? null]);
48
+ const covered = new Set(paidChoices(first.execution, checked, deps).map(choice));
49
+ if (!paidChoices(execution, view, deps).every((row) => covered.has(choice(row))))
50
+ return undefined;
51
+ storePreview(deps, preview, execution);
52
+ const stored = previewById(deps.db, view.revision.projectId, preview.id);
53
+ return stored === undefined ? undefined : { preview: stored, execution };
54
+ }
32
55
  export async function recoverProject(deps, projectId, raw,
33
56
  // Set only by an automatic review redo (`review-redo.ts`): see `activeConflict`.
34
57
  options = {}) {
@@ -258,7 +281,17 @@ options = {}) {
258
281
  : undefined;
259
282
  if (conflict !== undefined)
260
283
  return finish(conflictRefusal(conflict));
261
- const admitted = admitCheckedPreview(deps, prepared.plan.preview, prepared.plan.execution, ready.providers, recoveryKey(input, "admit"), requestHash("direct-recovery", input.baseRevisionId, input.action));
284
+ const admit = (plan) => admitCheckedPreview(deps, plan.preview, plan.execution, ready.providers, recoveryKey(input, "admit"), requestHash("direct-recovery", input.baseRevisionId, input.action));
285
+ let admitted = admit(prepared.plan);
286
+ // An automatic redo plans the run's unfinished steps the video waits on too, so one of
287
+ // them finishing while the services were checked leaves its plan stale. Its version is
288
+ // saved by then, and refusing would leave the new draw held until Try again: it is
289
+ // planned again here, under the same lock, when the services already checked cover it.
290
+ if (!admitted.ok && admitted.reason === "stale-preview" && superseded) {
291
+ const again = replanCovered(deps, prepared.plan, prepared.view);
292
+ if (again !== undefined)
293
+ admitted = admit(again);
294
+ }
262
295
  if (!admitted.ok)
263
296
  return finish(admitted);
264
297
  admittedHere = true;