@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
@@ -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) => {
@@ -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;
@@ -33,19 +33,25 @@ export function reviewHold(deps, work) {
33
33
  // Starts the redos reviews asked for, once their review step has finished: the item is made
34
34
  // again through Re-run's path (a new regeneration token saved as a new project version, then
35
35
  // its dependents rebuilt), so the redone item, its new review and everything after it are
36
- // ordinary recipe work. One at a time per verdict; a redo that cannot start leaves the item
37
- // flagged with the reason and releases what was waiting on it.
36
+ // ordinary recipe work. One at a time per project: two redos started together would each save
37
+ // a version on the one before, and the first one's admission would find the project changed,
38
+ // leaving its new draw held. A redo that cannot start leaves the item flagged with the reason
39
+ // and releases what was waiting on it.
38
40
  export function createReviewRedos() {
39
41
  let bound;
42
+ // The projects with a redo being started.
40
43
  const running = new Set();
41
- const kick = (projectId) => {
44
+ // `tried`: the verdicts this chain of redos already started. A redo that ended still
45
+ // waiting (its state never saved) is not started again by the chain, so two such redos
46
+ // can't start each other forever; the next review, run or restart starts a fresh chain.
47
+ const kick = (projectId, tried = new Set()) => {
42
48
  const deps = bound;
43
49
  if (deps === undefined)
44
50
  return;
45
51
  for (const verdict of pendingRedos(deps.db, projectId)) {
46
- if (running.has(verdict.id))
52
+ if (tried.has(verdict.id) || running.has(verdict.projectId))
47
53
  continue;
48
- running.add(verdict.id);
54
+ running.add(verdict.projectId);
49
55
  void startRedo(deps, verdict)
50
56
  .catch((error) => {
51
57
  deps.log.write("error", "review.redo", {
@@ -55,13 +61,15 @@ export function createReviewRedos() {
55
61
  setRedoState(deps.db, verdict.id, "failed", "Slopify hit an internal error while making this item again. Use Redo beside it; if it happens again, use Download diagnostics in Settings and report it.");
56
62
  })
57
63
  .finally(() => {
58
- running.delete(verdict.id);
64
+ running.delete(verdict.projectId);
59
65
  try {
60
66
  deps.runner.tick(verdict.projectId);
61
67
  }
62
68
  catch {
63
69
  // The next tick of this project picks the released work up.
64
70
  }
71
+ // The project's next waiting redo, on the version this one saved.
72
+ kick(verdict.projectId, new Set([...tried, verdict.id]));
65
73
  });
66
74
  }
67
75
  };
@@ -69,7 +77,7 @@ export function createReviewRedos() {
69
77
  bind: (deps) => {
70
78
  bound = deps;
71
79
  },
72
- kick,
80
+ kick: (projectId) => kick(projectId),
73
81
  };
74
82
  }
75
83
  // The verdicts whose redo is being started right now. Overrule may call off a redo only while
@@ -9,6 +9,11 @@ export function reservationKey(recipe, view) {
9
9
  const key = recipe.input.kind === "tts" ? `${recipe.input.logicalKey}:1` : recipe.key;
10
10
  if (view.revision.fingerprints[key] !== undefined)
11
11
  return key;
12
+ // A picture check planned once its scene was written has no entry of its own in a version
13
+ // saved while the picture still waited on its scene: it is held to the picture it checks.
14
+ const checked = /^review:(image:.+)$/.exec(recipe.key)?.[1];
15
+ if (checked !== undefined && view.revision.fingerprints[checked] !== undefined)
16
+ return checked;
12
17
  const future = recipe.input.kind === "tts"
13
18
  ? `audio:${recipe.input.segment}:future`
14
19
  : recipe.input.kind === "llm" && recipe.input.preparation
@@ -6,7 +6,7 @@ import { openExternalReview } from "../reviews/external-repo.js";
6
6
  import { externalReviewByFingerprint } from "../reviews/external-rows.js";
7
7
  import { reviewStages } from "../reviews/model.js";
8
8
  import { nextAttempt, reviewOutcome } from "../reviews/outcome.js";
9
- import { latestVerdict, saveVerdict } from "../reviews/repo.js";
9
+ import { latestVerdict, reviewedSameFile, saveVerdict } from "../reviews/repo.js";
10
10
  import { exportSnapshot } from "./runtime-export-inputs.js";
11
11
  import { lateValuesOf } from "./runtime-keywords.js";
12
12
  import { publishResult } from "./runtime-publication.js";
@@ -67,7 +67,9 @@ export async function executeAgentReviewRecipe(deps, context, piece) {
67
67
  const verdict = autoPassed ? { passed: true, reasons: [] } : known.verdict;
68
68
  if (known.state === "waiting" || verdict === null)
69
69
  return "waiting";
70
- const attempt = nextAttempt(latestVerdict(deps.db, projectId, itemKey), known.itemFingerprint);
70
+ const previous = latestVerdict(deps.db, projectId, itemKey);
71
+ const attempt = nextAttempt(previous, known.itemFingerprint, previous !== undefined &&
72
+ reviewedSameFile(deps.db, previous, context.work.revisionId, known.itemFingerprint));
71
73
  const outcome = autoPassed
72
74
  ? "auto-passed"
73
75
  : reviewOutcome({ passed: verdict.passed, mode, attempt, retries });
@@ -59,6 +59,16 @@ export function materializeAdmittedWork(deps, projectId) {
59
59
  reservations.find((row) => row.origin_revision === origin.origin_revision && row.work_key === futureKey(recipe));
60
60
  if (anchor === undefined || !desiredAnchor(deps, projectId, head, anchor))
61
61
  continue;
62
+ // A picture's check is unfolded from its picture once: one already reserved (an
63
+ // agent's review waiting for its answer is held, so it isn't among the allowed rows
64
+ // read above) is the version's check, not a placeholder to replace.
65
+ if (own === undefined &&
66
+ anchor.work_key !== recipe.key &&
67
+ recipe.key.startsWith("review:image:") &&
68
+ deps.db
69
+ .prepare("SELECT 1 FROM revision_work_reservations WHERE revision_id=? AND work_key=?")
70
+ .get(head, recipe.key) !== undefined)
71
+ continue;
62
72
  if (own !== undefined &&
63
73
  workPieces(deps.db, own.work_id).some((piece) => piece.submittedAt !== null || piece.state === "done"))
64
74
  continue;
@@ -151,6 +161,10 @@ function futureKey(recipe) {
151
161
  return "research:planner";
152
162
  if (recipe.key === "article:continuation")
153
163
  return "article:body";
164
+ // A picture's check unfolds with the picture once its scene is written.
165
+ const picture = /^review:(image:.+)$/.exec(recipe.key);
166
+ if (picture?.[1] !== undefined)
167
+ return picture[1];
154
168
  // A short's images and render unfold from its image prompts, admitted with them: under the
155
169
  // pick on a first run, or on their own when one short is made again and the pick is kept.
156
170
  // The prompts unfold from the pick's answer.
@@ -1,11 +1,12 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { z } from "zod";
3
4
  import { catalogueSchema } from "../../catalog/schema.js";
4
- import { fingerprint } from "../../kernel/runner/work.js";
5
- import { getRevisionView, readyOutput, withEarlierJoins } from "../revisions/view.js";
5
+ import { narrationJoinPiecesOfProject, narrationJoinsOfProject, } from "../revisions/manifest-repo.js";
6
+ import { getRevisionView, readyOutput } from "../revisions/view.js";
6
7
  import { outputPath } from "../storage/layout.js";
7
- import { referencedAssetsAvailable, retainedNarrationPieces } from "./narration-history.js";
8
- import { applyProvidedReviews } from "./provided-review.js";
8
+ import { forgetNarrationHistory, referencedAssetsAvailable, retainedNarrationHistory, } from "./narration-history.js";
9
+ import { applyReviews, providedReviews } from "./provided-review.js";
9
10
  import { textRecipes } from "./recipe-text.js";
10
11
  import { planRevisionWork } from "./recipe-work.js";
11
12
  export function executionCatalogue(catalogue, config) {
@@ -57,18 +58,21 @@ export function workLlm(db, workId, choice, label) {
57
58
  // few dozen times over a run; at 240 it happened tens of thousands of times and the server
58
59
  // spent its whole time planning instead of answering.
59
60
  //
60
- // The plan is kept and handed back while nothing in the database has changed, which SQLite
61
- // counts for us. That is a blunt test on purpose: a write anywhere - another project, another
62
- // revision - throws the plan away and it is derived again. It can never hand back a plan from
63
- // after a write it has not seen, which is the only direction that would matter, because a
64
- // stale plan would start the wrong work.
61
+ // The plan is kept and handed back while everything it is derived from is unchanged. It used
62
+ // to be thrown away on any write to the database at all, which during a run is every finished
63
+ // step of every project, and every write a step makes on its way (its attempt, its cost, its
64
+ // telemetry): a dozen runs at once derived the plan of a 2-hour video several times a second
65
+ // and the server stopped answering. Now the key is what the plan reads, each part read afresh
66
+ // on every call (`planInputs`): the version, its outputs and pieces and whether each file is on
67
+ // disk, the article and notes it reads off disk, the project's narration history and narration
68
+ // joins, the uploads it refers to, its saved provided-content reviews and the catalogue. What
69
+ // those were read from changes, the key changes. A stale plan would start the wrong work, so a
70
+ // test (`runtime-plan-inputs.test.ts`) lists every table a derivation reads: one read the key
71
+ // doesn't cover fails it.
65
72
  // Per database, never shared between them: two of them (the app and a mirror, or two tests)
66
73
  // can hold the same project under the same id, and one's plan is not the other's.
67
74
  const kept = new WeakMap();
68
- const changeCount = z.object({ changes: z.number() });
69
- function writesSoFar(deps) {
70
- return changeCount.parse(deps.db.prepare("SELECT total_changes() AS changes").get()).changes;
71
- }
75
+ const keptPlans = 48;
72
76
  // Two catalogues that differ give different plans, so the catalogue belongs in the key. Its
73
77
  // date and shape identify it without hashing the whole of it on every call.
74
78
  function catalogueMark(catalogue) {
@@ -80,47 +84,87 @@ function catalogueMark(catalogue) {
80
84
  Object.keys(catalogue.providers).length,
81
85
  ].join("/");
82
86
  }
83
- // What the plan was derived from, beyond the database: whether each output and piece is
84
- // selected and whether its file is still on disk. A file deleted by hand is no write at all,
85
- // so `total_changes()` would never notice it, and the plan would go on reusing work whose
86
- // output is gone. Walking a few hundred rows is nothing beside deriving the plan again.
87
+ const hash = (text) => createHash("sha256").update(text).digest("base64url");
88
+ // What the plan reads of the version: its settings and contents, whether each output and
89
+ // piece is selected and whether its file is still on disk. A file deleted by hand is no write at
90
+ // all, and the plan must stop reusing work whose output is gone. A saved output or piece never
91
+ // changes under its record id (only which are selected does), so the id stands for its record.
87
92
  function viewMark(view) {
88
- const rows = [String(view.articleMarkdown?.length ?? -1)];
93
+ const rows = [
94
+ JSON.stringify(view.revision),
95
+ String(view.current),
96
+ view.articleMarkdown === null ? "-" : `+${view.articleMarkdown}`,
97
+ ];
89
98
  for (const row of view.outputs)
90
99
  rows.push(`o${row.recordId}:${row.selected ? 1 : 0}${row.available ? 1 : 0}:${row.fingerprint}`);
91
100
  for (const row of view.pieces)
92
101
  rows.push(`p${row.recordId}:${row.selected ? 1 : 0}${row.available ? 1 : 0}:${row.fingerprint}`);
93
- return fingerprint(rows.join("\n"));
102
+ return hash(rows.join("\n"));
94
103
  }
95
- export function executionPlan(deps, view, catalogue) {
96
- const key = `${view.revision.projectId}/${view.revision.id}/${catalogueMark(catalogue)}/${viewMark(view)}`;
97
- const changes = writesSoFar(deps);
98
- const forDb = kept.get(deps.db) ?? new Map();
99
- kept.set(deps.db, forDb);
100
- const held = forDb.get(key);
101
- if (held !== undefined && held.changes === changes)
102
- return held.plan;
103
- const plan = derivePlan(deps, view, catalogue);
104
- // A cache, not a store: a handful of revisions is all a run needs at once.
105
- if (forDb.size > 8)
106
- forDb.clear();
107
- forDb.set(key, { changes, plan });
108
- return plan;
109
- }
110
- function derivePlan(deps, view, catalogue) {
104
+ function planInputs(deps, view) {
111
105
  const textOutput = (role) => {
112
106
  const row = readyOutput(view, { role });
113
107
  return row === undefined
114
108
  ? null
115
109
  : readFileSync(outputPath(deps.paths, view.revision.projectId, row.output.path), "utf8");
116
110
  };
117
- const payloads = view.pieces.filter((piece) => piece.selected && piece.piece.state === "done" && piece.piece.payload !== null);
118
- const resolved = {
111
+ const { projectId } = view.revision;
112
+ return {
119
113
  articleMarkdown: view.revision.content.articleEdited === true ||
120
114
  view.revision.config.sources.article !== "generate"
121
115
  ? view.articleMarkdown
122
116
  : textOutput("article_md"),
123
117
  researchNotes: textOutput("notes"),
118
+ history: retainedNarrationHistory(deps, projectId),
119
+ referenced: referencedAssetsAvailable(deps, projectId, Object.values(view.revision.content.narrationOverrides).flatMap((value) => value.kind === "asset" ? [value.assetId] : [])),
120
+ earlierJoins: narrationJoinsOfProject(deps.db, projectId),
121
+ earlierJoinPieces: narrationJoinPiecesOfProject(deps.db, projectId),
122
+ reviews: providedReviews(deps.db, view.revision.id),
123
+ };
124
+ }
125
+ function inputsMark(inputs) {
126
+ const record = (row) => `${row.recordId}:${row.selected ? 1 : 0}:${row.fingerprint}:${row.assetId}`;
127
+ return hash([
128
+ inputs.articleMarkdown === null ? "-" : `+${inputs.articleMarkdown}`,
129
+ inputs.researchNotes === null ? "-" : `+${inputs.researchNotes}`,
130
+ inputs.history.mark,
131
+ inputs.referenced.join(","),
132
+ inputs.earlierJoins.map((row) => `${record(row)}:${row.state}`).join(","),
133
+ inputs.earlierJoinPieces.map(record).join(","),
134
+ JSON.stringify(inputs.reviews),
135
+ ].join("\n\u0000"));
136
+ }
137
+ // Forgets the plans and planning inputs kept for this database, so the next plan is derived
138
+ // from fresh reads (tests compare the two).
139
+ export function forgetPlanInputs(db) {
140
+ kept.delete(db);
141
+ forgetNarrationHistory(db);
142
+ }
143
+ export function executionPlan(deps, view, catalogue) {
144
+ const inputs = planInputs(deps, view);
145
+ const key = `${view.revision.projectId}/${view.revision.id}/${catalogueMark(catalogue)}/${viewMark(view)}/${inputsMark(inputs)}`;
146
+ const forDb = kept.get(deps.db) ?? new Map();
147
+ kept.set(deps.db, forDb);
148
+ const held = forDb.get(key);
149
+ if (held !== undefined) {
150
+ forDb.delete(key);
151
+ forDb.set(key, held);
152
+ return held;
153
+ }
154
+ const plan = derivePlan(view, catalogue, inputs);
155
+ // A cache, not a store, and the least recently used goes first: a dozen runs at once, each
156
+ // with the versions its held work came from (a redo plans those too). Clearing it all past
157
+ // nine threw every project's plan away before that project asked again.
158
+ forDb.set(key, plan);
159
+ if (forDb.size > keptPlans)
160
+ forDb.delete(forDb.keys().next().value);
161
+ return plan;
162
+ }
163
+ function derivePlan(view, catalogue, inputs) {
164
+ const payloads = view.pieces.filter((piece) => piece.selected && piece.piece.state === "done" && piece.piece.payload !== null);
165
+ const resolved = {
166
+ articleMarkdown: inputs.articleMarkdown,
167
+ researchNotes: inputs.researchNotes,
124
168
  };
125
169
  const research = matchingResearch({
126
170
  config: view.revision.config,
@@ -129,18 +173,20 @@ function derivePlan(deps, view, catalogue) {
129
173
  catalogue,
130
174
  resolved,
131
175
  }, payloads);
132
- const history = retainedNarrationPieces(deps, view.revision.projectId);
176
+ const history = inputs.history.pieces;
133
177
  const available = new Set([
134
178
  ...history
135
179
  .filter((row) => row.available && row.assetId !== null)
136
180
  .flatMap((row) => (row.assetId === null ? [] : [row.assetId])),
137
- ...referencedAssetsAvailable(deps, view.revision.projectId, Object.values(view.revision.content.narrationOverrides).flatMap((value) => value.kind === "asset" ? [value.assetId] : [])),
181
+ ...inputs.referenced,
138
182
  ...view.outputs.filter((row) => row.available).map((row) => row.assetId),
139
183
  ...view.pieces
140
184
  .filter((row) => row.available && row.assetId !== null)
141
185
  .flatMap((row) => (row.assetId === null ? [] : [row.assetId])),
142
186
  ]);
143
- return applyProvidedReviews(deps.db, view.revision.id, planRevisionWork(view.revision, withEarlierJoins(deps, view), catalogue, available, {
187
+ return applyReviews(inputs.reviews, planRevisionWork(view.revision,
188
+ // The view with the narration joins of every version of the project (`withEarlierJoins`).
189
+ { ...view, earlierJoins: inputs.earlierJoins, earlierJoinPieces: inputs.earlierJoinPieces }, catalogue, available, {
144
190
  ...resolved,
145
191
  ...(research === undefined ? {} : { research }),
146
192
  }, history));
@@ -6,7 +6,7 @@ import { editSettings } from "../../kernel/ports/settings-places.js";
6
6
  import { plainText } from "../article/plain.js";
7
7
  import { defaultReviewPrompts, narrationItemKey, reviewStages, } from "../reviews/model.js";
8
8
  import { nextAttempt, reviewOutcome } from "../reviews/outcome.js";
9
- import { latestVerdict, saveVerdict } from "../reviews/repo.js";
9
+ import { latestVerdict, reviewedSameFile, saveVerdict } from "../reviews/repo.js";
10
10
  import { parseVerdict, reviewMessages } from "../reviews/verdict.js";
11
11
  import { isReadyOutput } from "../revisions/view.js";
12
12
  import { pickedShortsOf } from "../shorts/clips.js";
@@ -52,7 +52,8 @@ export async function executeReviewRecipe(deps, context, providers, piece) {
52
52
  const snapshot = exportSnapshot(deps, context, piece);
53
53
  const material = reviewMaterial(deps, context, snapshot, stage, itemKey, prompt);
54
54
  const previous = latestVerdict(deps.db, context.work.projectId, itemKey);
55
- const attempt = nextAttempt(previous, material.itemFingerprint);
55
+ const attempt = nextAttempt(previous, material.itemFingerprint, previous !== undefined &&
56
+ reviewedSameFile(deps.db, previous, context.work.revisionId, material.itemFingerprint));
56
57
  const level = thinking === null ? undefined : z.enum(thinkingModes).parse(thinking);
57
58
  const call = workLlm(deps.db, context.work.workId, { provider, model, thinking: level }, piece.key);
58
59
  if (!context.maySubmit(piece.id))
@@ -63,16 +63,19 @@ export function transitionRevisionWork(deps, input) {
63
63
  carried.add(row.work_key);
64
64
  }
65
65
  }
66
- const live = db.prepare("SELECT id FROM revision_work WHERE project_id=?").all(input.projectId);
67
- for (const row of live) {
68
- const id = z.string().parse(row.id);
69
- db.prepare(`UPDATE revision_work_pieces SET dispatch_state=CASE WHEN submitted_at IS NOT NULL THEN 'draining' ELSE 'held' END WHERE work_id=? AND state!='done' AND id NOT IN (SELECT piece_id FROM revision_work_reservations WHERE revision_id=? AND piece_id IS NOT NULL)`).run(id, input.revisionId);
70
- const keeps = db
71
- .prepare("SELECT 1 FROM revision_work_reservations WHERE revision_id=? AND work_id=?")
72
- .get(input.revisionId, id) !== undefined;
73
- if (!keeps)
74
- db.prepare(`UPDATE revision_work SET dispatch_state=CASE WHEN EXISTS(SELECT 1 FROM attempts WHERE work_id=?) OR EXISTS(SELECT 1 FROM revision_work_pieces WHERE work_id=? AND submitted_at IS NOT NULL) THEN 'draining' ELSE 'held' END WHERE id=? AND state!='done'`).run(id, id, id);
75
- }
66
+ // Every step of the project the new version doesn't keep: its unfinished pieces and the
67
+ // step itself are held, or draining once something of them was sent or attempted. Two
68
+ // statements over the whole project, not three per step: a project made a few times over
69
+ // has thousands of steps, and the save held the server for seconds.
70
+ db.prepare(`UPDATE revision_work_pieces SET dispatch_state=CASE WHEN submitted_at IS NOT NULL THEN 'draining' ELSE 'held' END
71
+ WHERE work_id IN (SELECT id FROM revision_work WHERE project_id=?) AND state!='done'
72
+ AND id NOT IN (SELECT piece_id FROM revision_work_reservations WHERE revision_id=? AND piece_id IS NOT NULL)`).run(input.projectId, input.revisionId);
73
+ db.prepare(`UPDATE revision_work SET dispatch_state=CASE
74
+ WHEN EXISTS(SELECT 1 FROM attempts a WHERE a.work_id=revision_work.id)
75
+ OR EXISTS(SELECT 1 FROM revision_work_pieces p WHERE p.work_id=revision_work.id AND p.submitted_at IS NOT NULL)
76
+ THEN 'draining' ELSE 'held' END
77
+ WHERE project_id=? AND state!='done'
78
+ AND NOT EXISTS(SELECT 1 FROM revision_work_reservations r WHERE r.revision_id=? AND r.work_id=revision_work.id)`).run(input.projectId, input.revisionId);
76
79
  db.prepare(`DELETE FROM revision_work_reservations WHERE project_id=? AND revision_id=? AND work_key NOT IN (SELECT work_key FROM revision_work_reservations WHERE revision_id=?)`).run(input.projectId, input.baseRevisionId, input.revisionId);
77
80
  for (const [key, fp] of Object.entries(input.fingerprints)) {
78
81
  if (carried.has(key))
@@ -1,10 +1,12 @@
1
1
  // Which try at the item this review looks at. A redo Slopify started itself carries the
2
2
  // count on; anything else (a first review, an item the person changed or had made again)
3
- // starts at one. The same output reviewed again keeps its number.
4
- export function nextAttempt(previous, itemFingerprint) {
3
+ // starts at one. The same output reviewed again keeps its number, and so does the same file
4
+ // under another fingerprint (`sameFile`, from `reviewedSameFile`): an item flagged after its
5
+ // last try stays flagged rather than being sent back from the first try again.
6
+ export function nextAttempt(previous, itemFingerprint, sameFile = false) {
5
7
  if (previous === undefined)
6
8
  return 1;
7
- if (previous.itemFingerprint === itemFingerprint)
9
+ if (previous.itemFingerprint === itemFingerprint || sameFile)
8
10
  return previous.attempt;
9
11
  if (previous.outcome === "redo" && previous.action === null && previous.redoState !== "failed")
10
12
  return previous.attempt + 1;
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { internalError } from "../../kernel/errors.js";
3
3
  import { actors } from "../agents/model.js";
4
4
  import { reviewAnswerers, reviewStages } from "./model.js";
5
+ import { reviewedOutputKey } from "./view.js";
5
6
  const rowSchema = z.object({
6
7
  id: z.string(),
7
8
  project_id: z.string(),
@@ -93,6 +94,17 @@ export function pendingRedos(db, projectId) {
93
94
  .prepare("SELECT * FROM review_verdicts WHERE redo_state='pending' AND project_id=? ORDER BY rowid")
94
95
  .all(projectId)).map(recordOf);
95
96
  }
97
+ // Whether this verdict looked at the very file a version now holds under `itemFingerprint`. A
98
+ // version that keeps a file can stamp it with another fingerprint (a deferred article settles
99
+ // on its planned one), and the same file is no new try at the item (`nextAttempt`).
100
+ export function reviewedSameFile(db, verdict, revisionId, itemFingerprint) {
101
+ const workKey = reviewedOutputKey(verdict.itemKey);
102
+ return (db
103
+ .prepare(`SELECT 1 FROM revision_outputs a JOIN revision_outputs b ON b.asset_id=a.asset_id
104
+ WHERE a.project_id=? AND a.revision_id=? AND a.work_key=? AND a.fingerprint=?
105
+ AND b.project_id=? AND b.revision_id=? AND b.work_key=? AND b.fingerprint=? LIMIT 1`)
106
+ .get(verdict.projectId, verdict.revisionId, workKey, verdict.itemFingerprint, verdict.projectId, revisionId, workKey, itemFingerprint) !== undefined);
107
+ }
96
108
  export function setRedoState(db, id, state, error = null) {
97
109
  db.prepare("UPDATE review_verdicts SET redo_state=?, redo_error=? WHERE id=?").run(state, error, id);
98
110
  }
@@ -1,5 +1,5 @@
1
1
  import { readFileSync, statSync } from "node:fs";
2
- import { outputPath } from "../storage/layout.js";
2
+ import { outputPath, outputPaths } from "../storage/layout.js";
3
3
  import { narrationJoinPiecesOfProject, narrationJoinsOfProject } from "./manifest-repo.js";
4
4
  import { currentRevisionId, outputsForRevision, piecesForRevision, revisionById } from "./repo.js";
5
5
  export function getRevisionView(deps, projectId, revisionId) {
@@ -16,6 +16,7 @@ export function getRevisionView(deps, projectId, revisionId) {
16
16
  if (typeof row.id === "string" && typeof row.path === "string")
17
17
  paths.set(row.id, row.path);
18
18
  const onDisk = new Map();
19
+ const pathOf = outputPaths(deps.paths, projectId);
19
20
  const available = (assetId) => {
20
21
  const known = onDisk.get(assetId);
21
22
  if (known !== undefined)
@@ -23,8 +24,7 @@ export function getRevisionView(deps, projectId, revisionId) {
23
24
  const path = paths.get(assetId);
24
25
  if (path === undefined)
25
26
  throw new Error(`Revision asset ${assetId} is not registered.`);
26
- const found = statSync(outputPath(deps.paths, projectId, path), { throwIfNoEntry: false })?.isFile() ===
27
- true;
27
+ const found = statSync(pathOf(path), { throwIfNoEntry: false })?.isFile() === true;
28
28
  onDisk.set(assetId, found);
29
29
  return found;
30
30
  };
@@ -28,8 +28,12 @@ export function isLocalCliProvider(id) {
28
28
  }
29
29
  // How many calls to a command-line tool run at once. Each Codex image is its own job - its
30
30
  // own folder and thread - so four are drawn side by side; the text CLIs keep three.
31
- export function localCliConcurrency(id) {
32
- return id === "codex-image" ? 4 : 3;
31
+ // SLOPIFY_CODEX_IMAGES_AT_ONCE (1 to 8) draws more or fewer when the account allows it.
32
+ export function localCliConcurrency(id, env) {
33
+ if (id !== "codex-image")
34
+ return 3;
35
+ const asked = env.SLOPIFY_CODEX_IMAGES_AT_ONCE ?? "";
36
+ return /^[1-8]$/.test(asked) ? Number(asked) : 4;
33
37
  }
34
38
  export const systemVoiceProvider = "system-voice";
35
39
  // A provider Slopify's model list (models.yaml) does not carry: an agent CLI lists its own
@@ -23,6 +23,21 @@ export function outputPath(paths, projectId, relativePath) {
23
23
  return contained(projectDir(paths, projectId), relativePath);
24
24
  return contained(projectDir(paths, projectId), paths.places?.placeOf(projectId, relativePath) ?? relativePath);
25
25
  }
26
+ // The same for many of one project's stored paths at once: whether it is a studio sample and
27
+ // where its folder is are looked up once, not for every file (each is a database read and a
28
+ // look on disk). For use within one synchronous pass; a later pass asks again.
29
+ export function outputPaths(paths, projectId) {
30
+ let folder;
31
+ return (relativePath) => {
32
+ folder ??= {
33
+ sample: paths.samples?.has(projectId) === true,
34
+ dir: projectDir(paths, projectId),
35
+ };
36
+ return contained(folder.dir, folder.sample
37
+ ? relativePath
38
+ : (paths.places?.placeOf(projectId, relativePath) ?? relativePath));
39
+ };
40
+ }
26
41
  // Scheduled backups (slices/backups) land in paths.backups unless the user picks another
27
42
  // folder. Installs from before 3.0 keep it inside the projects root, since that is the one
28
43
  // folder an older Docker install shares with the host; newer ones have it beside Projects.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gentbajko/slopify",
3
- "version": "4.5.2",
3
+ "version": "4.5.3",
4
4
  "description": "Turn a prompt into a finished video, locally, with your own provider keys",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Gent Bajko",